Add Android security Phase 0
@@ -4,6 +4,12 @@ Status: **Plan**. Android already has several useful protections, but it does no
|
|||||||
|
|
||||||
Related: [ENCRYPTION_PLAN.md](./ENCRYPTION_PLAN.md), [SECURITY_REVIEW.md](./SECURITY_REVIEW.md), and [TODO.md](./TODO.md).
|
Related: [ENCRYPTION_PLAN.md](./ENCRYPTION_PLAN.md), [SECURITY_REVIEW.md](./SECURITY_REVIEW.md), and [TODO.md](./TODO.md).
|
||||||
|
|
||||||
|
## Implementation progress (2026-11-03)
|
||||||
|
|
||||||
|
- Implemented: explicit Android cleartext denial and backup/data-extraction exclusions; removed the wildcard Cordova origin and unused broad `FileProvider`; DAV now requires HTTPS, rejects embedded credentials/fragments, stays on the configured origin, and does not follow redirects; saved attachment names are sanitized; notification previews and native logs no longer expose mailbox content; debug APKs are labeled as debug and signed release builds require environment-provided signing credentials.
|
||||||
|
- Tested: DAV URL policy and attachment-name policy have Android unit tests. The debug Android build and unit tests pass, as does the Node test suite.
|
||||||
|
- Still open: invalid-certificate integration tests, device-level review of the merged release APK, private notification preference UI, app lock/biometric unlock, full vault lifecycle testing, and Android OpenPGP. OpenPGP work remains gated on an independent cryptography/security review.
|
||||||
|
|
||||||
## Goals and limits
|
## Goals and limits
|
||||||
|
|
||||||
Protect account credentials and locally cached mail if app files are copied; prevent untrusted mail or renderer content from gaining native capabilities; protect message content in transit; give users control over sensitive previews and local unlock; and bring Android OpenPGP behavior up to the security guarantees already implemented on desktop.
|
Protect account credentials and locally cached mail if app files are copied; prevent untrusted mail or renderer content from gaining native capabilities; protect message content in transit; give users control over sensitive previews and local unlock; and bring Android OpenPGP behavior up to the security guarantees already implemented on desktop.
|
||||||
|
|||||||
@@ -1,119 +1,119 @@
|
|||||||
# Architecture
|
# 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.
|
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
|
## 1. Runtime layout
|
||||||
|
|
||||||
### Desktop shell
|
### Desktop shell
|
||||||
|
|
||||||
- `desktop/main.cjs` is the privileged process.
|
- `desktop/main.cjs` is the privileged process.
|
||||||
- It owns account storage, mail sync, IMAP/SMTP connectivity, DAV sync, and OpenPGP key handling.
|
- 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.
|
- 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`.
|
- `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
|
### Renderer UI
|
||||||
|
|
||||||
The browser UI is rendered from canonical web assets in the repository root; `www/` is generated for Capacitor:
|
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.
|
- `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.
|
- `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.
|
- 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.
|
- 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
|
### Android client
|
||||||
|
|
||||||
The Android app reuses the web UI in a Capacitor shell (`android/`, `capacitor.config.json`).
|
The Android app reuses the web UI in a Capacitor shell (`android/`, `capacitor.config.json`).
|
||||||
|
|
||||||
- The same browser UI runs inside the Android app.
|
- The same browser UI runs inside the Android app.
|
||||||
- Native Android services handle background sync, notification behavior, and secure storage.
|
- 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.
|
- The desktop and Android implementations intentionally share the same mail and account model so the feature surface stays aligned.
|
||||||
|
|
||||||
## 2. Core responsibilities
|
## 2. Core responsibilities
|
||||||
|
|
||||||
### Mail and account state
|
### Mail and account state
|
||||||
|
|
||||||
The main process owns the canonical account model and persists it in an encrypted store:
|
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.
|
- `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.
|
- `dav-accounts.enc` stores CalDAV/CardDAV credentials and server config.
|
||||||
- `pgp-keys.enc` stores OpenPGP keys and trust data.
|
- `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.
|
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
|
### Mail sync pipeline
|
||||||
|
|
||||||
The desktop app follows a background sync model:
|
The desktop app follows a background sync model:
|
||||||
|
|
||||||
1. The renderer asks the main process for a folder sync or inbox refresh.
|
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.
|
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`).
|
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.
|
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.
|
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
|
### Message send path
|
||||||
|
|
||||||
The send flow is also centralized in the main process:
|
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 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 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 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.
|
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
|
## 3. Security boundary
|
||||||
|
|
||||||
The current architecture takes a strict trust split:
|
The current architecture takes a strict trust split:
|
||||||
|
|
||||||
- renderer: UI, user interaction, local conveniences
|
- renderer: UI, user interaction, local conveniences
|
||||||
- main process: network access, cryptographic operations, permission prompts, OS secure storage
|
- main process: network access, cryptographic operations, permission prompts, OS secure storage
|
||||||
|
|
||||||
This boundary is important for encryption and safety checks:
|
This boundary is important for encryption and safety checks:
|
||||||
|
|
||||||
- OpenPGP key selection and trust updates are confirmed in the main process.
|
- 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.
|
- 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.
|
- 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.
|
- Send-time downgrade checks happen in the main process rather than only in UI logic.
|
||||||
- External links open only after a native confirmation dialog.
|
- 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.
|
- 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.
|
- Credentials and private keys are stored with the OS keyring, not in plain JSON files.
|
||||||
|
|
||||||
## 4. OpenPGP subsystem
|
## 4. OpenPGP subsystem
|
||||||
|
|
||||||
The OpenPGP implementation is split into focused modules:
|
The OpenPGP implementation is split into focused modules:
|
||||||
|
|
||||||
- `desktop/pgp-keystore.cjs` stores contacts, trust, key material, and settings.
|
- `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-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/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.
|
- `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.
|
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.
|
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
|
## 5. Data flow patterns
|
||||||
|
|
||||||
- Account setup and edits flow from the UI into IPC, then into the encrypted main-process storage.
|
- 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.
|
- 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.
|
- 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.
|
- Search, folder listing, and draft operations reuse the same account model across both desktop and Android versions.
|
||||||
|
|
||||||
## 6. Release and packaging model
|
## 6. Release and packaging model
|
||||||
|
|
||||||
The project packages multiple platforms from the same codebase:
|
The project packages multiple platforms from the same codebase:
|
||||||
|
|
||||||
- `npm run dist:win` for Windows installer/portable builds
|
- `npm run dist:win` for Windows installer/portable builds
|
||||||
- `npm run dist:linux` for Linux AppImage and Debian builds
|
- `npm run dist:linux` for Linux AppImage and Debian builds
|
||||||
- Android builds via Capacitor (`npm run android:apk`)
|
- Android builds via Capacitor (`npm run android:apk`)
|
||||||
|
|
||||||
The app version is managed through package metadata and the Electron build config in `package.json`.
|
The app version is managed through package metadata and the Electron build config in `package.json`.
|
||||||
|
|
||||||
## 7. Key architectural principles
|
## 7. Key architectural principles
|
||||||
|
|
||||||
- Keep privileged operations in the main process.
|
- Keep privileged operations in the main process.
|
||||||
- Keep security rules in trusted code rather than the UI.
|
- Keep security rules in trusted code rather than the UI.
|
||||||
- Store secrets in OS-backed secure storage whenever the platform supports it.
|
- 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.
|
- 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.
|
- 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.
|
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.
|
||||||
|
|||||||
@@ -1,101 +1,101 @@
|
|||||||
# 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 OpenPGP support and an independent human security review are still open. See [ANDROID_SECURITY_PLAN.md](./ANDROID_SECURITY_PLAN.md) for the broader Android security roadmap. Automated review findings and their fixes are documented in [SECURITY_REVIEW.md](./SECURITY_REVIEW.md); see [TODO.md](./TODO.md) for follow-up work.
|
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. See [ANDROID_SECURITY_PLAN.md](./ANDROID_SECURITY_PLAN.md) for the broader Android security roadmap. 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)
|
||||||
|
|
||||||
| Option | Pros | Cons |
|
| Option | Pros | Cons |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| **OpenPGP** | Interoperates with Thunderbird, Proton, Mailvelope, GnuPG and K-9/OpenKeychain. No certificate authority needed. | Key verification is manual. |
|
| **OpenPGP** | Interoperates with Thunderbird, Proton, Mailvelope, GnuPG and K-9/OpenKeychain. No certificate authority needed. | Key verification is manual. |
|
||||||
| S/MIME | Native in Outlook and Apple Mail. | Needs CA-issued certificates; poor fit for personal accounts. |
|
| S/MIME | Native in Outlook and Apple Mail. | Needs CA-issued certificates; poor fit for personal accounts. |
|
||||||
|
|
||||||
Decision: OpenPGP only for v1; S/MIME may follow later.
|
Decision: OpenPGP only for v1; S/MIME may follow later.
|
||||||
|
|
||||||
- Library: [OpenPGP.js](https://github.com/openpgpjs/openpgpjs) (`openpgp`), pure JS, usable in Electron and the Android WebView.
|
- Library: [OpenPGP.js](https://github.com/openpgpjs/openpgpjs) (`openpgp`), pure JS, usable in Electron and the Android WebView.
|
||||||
- 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 and Web Key Directory. Desktop key-server lookup and publication are described in section 9.
|
- 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
|
||||||
|
|
||||||
**Private keys**
|
**Private keys**
|
||||||
- One or more keys per account; never stored unprotected and never sent anywhere.
|
- One or more keys per account; never stored unprotected and never sent anywhere.
|
||||||
- Always protected by a passphrase (minimum 8 characters). On desktop the whole key store is also encrypted with Electron `safeStorage` (the OS credential store).
|
- Always protected by a passphrase (minimum 8 characters). On desktop the whole key store is also encrypted with Electron `safeStorage` (the OS credential store).
|
||||||
- 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. 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.
|
- 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, key-server lookup, and 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
|
||||||
|
|
||||||
- Compose: lock toggle, on by default when every recipient has a key. Never silently downgrade; offer to send unencrypted or cancel.
|
- Compose: lock toggle, on by default when every recipient has a key. Never silently downgrade; offer to send unencrypted or cancel.
|
||||||
- Reader: status line such as "Encrypted and signed by X (verified)" or a warning for bad/unknown signatures.
|
- Reader: status line such as "Encrypted and signed by X (verified)" or a warning for bad/unknown signatures.
|
||||||
- Message list: lock icon for encrypted mail.
|
- Message list: lock icon for encrypted mail.
|
||||||
- Settings: **Encryption keys** (Phase 1) for create, import, export, delete.
|
- Settings: **Encryption keys** (Phase 1) for create, import, export, delete.
|
||||||
- Interactions: search and rules cannot read encrypted bodies (subject/sender stay plaintext); do not cache decrypted bodies; run link warnings and attachment previews only after decryption; encrypt the Sent copy to the sender's own key too.
|
- Interactions: search and rules cannot read encrypted bodies (subject/sender stay plaintext); do not cache decrypted bodies; run link warnings and attachment previews only after decryption; encrypt the Sent copy to the sender's own key too.
|
||||||
|
|
||||||
## 4. Threat model and limits
|
## 4. Threat model and limits
|
||||||
|
|
||||||
- Protects content from the mail server and network observers.
|
- Protects content from the mail server and network observers.
|
||||||
- Does not protect metadata (sender, recipients, subject, timestamps).
|
- Does not protect metadata (sender, recipients, subject, timestamps).
|
||||||
- A compromised device, or a stolen key plus passphrase, defeats it.
|
- A compromised device, or a stolen key plus passphrase, defeats it.
|
||||||
- Losing the key means losing access to old encrypted mail; backups are the user's responsibility.
|
- Losing the key means losing access to old encrypted mail; backups are the user's responsibility.
|
||||||
|
|
||||||
## 5. Phases
|
## 5. Phases
|
||||||
|
|
||||||
| Phase | Scope | Status |
|
| Phase | Scope | Status |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| 1 | Foundation: OpenPGP.js, passphrase-protected key store (OS credential store on desktop), generate/import/export/delete, revocation certificate, unit tests, Settings UI | Done (desktop) |
|
| 1 | Foundation: OpenPGP.js, passphrase-protected key store (OS credential store on desktop), generate/import/export/delete, revocation certificate, unit tests, Settings UI | Done (desktop) |
|
||||||
| 2 | Receive: detect PGP/MIME and inline PGP, decrypt on open, verify signatures, status UI, missing-key and wrong-passphrase handling | Done (desktop) |
|
| 2 | Receive: detect PGP/MIME and inline PGP, decrypt on open, verify signatures, status UI, missing-key and wrong-passphrase handling | Done (desktop) |
|
||||||
| 3 | Send: public-key keyring and contact import, encrypt and sign on compose, encrypted Sent copy, downgrade warnings | Done (desktop) |
|
| 3 | Send: public-key keyring and contact import, encrypt and sign on compose, encrypted Sent copy, downgrade warnings | Done (desktop) |
|
||||||
| 4 | Trust and polish: fingerprint verification, key-change warnings, passphrase cache timeout, Android Keystore and biometric unlock | Desktop done; Android open |
|
| 4 | Trust and polish: fingerprint verification, key-change warnings, passphrase cache timeout, Android Keystore and biometric unlock | Desktop done; Android open |
|
||||||
| 5 | Interop testing with Thunderbird and GnuPG, large attachments, multiple recipients, corrupted payloads | Automated, GnuPG and manual Thunderbird interop checks done |
|
| 5 | Interop testing with Thunderbird and GnuPG, large attachments, multiple recipients, corrupted payloads | Automated, GnuPG and manual Thunderbird interop checks done |
|
||||||
| 6 | Docs, security review, release | Docs and release done; independent review open |
|
| 6 | Docs, security review, release | Docs and release done; independent review open |
|
||||||
|
|
||||||
## 6. Phase 1 implementation notes
|
## 6. Phase 1 implementation notes
|
||||||
|
|
||||||
- [desktop/pgp-keystore.cjs](./desktop/pgp-keystore.cjs): platform-independent key store with an injected storage backend.
|
- [desktop/pgp-keystore.cjs](./desktop/pgp-keystore.cjs): platform-independent key store with an injected storage backend.
|
||||||
- [desktop/main.cjs](./desktop/main.cjs): wraps the store with `safeStorage` (`pgp-keys.enc` in the user data folder) and exposes `pgp:*` IPC handlers; key files are saved through native dialogs.
|
- [desktop/main.cjs](./desktop/main.cjs): wraps the store with `safeStorage` (`pgp-keys.enc` in the user data folder) and exposes `pgp:*` IPC handlers; key files are saved through native dialogs.
|
||||||
- [desktop/preload.cjs](./desktop/preload.cjs): exposes `daybreakMail.pgp`.
|
- [desktop/preload.cjs](./desktop/preload.cjs): exposes `daybreakMail.pgp`.
|
||||||
- [pgp-ui.js](./pgp-ui.js): Settings → **Encryption keys**. Hidden on platforms without a key store (Android until Phase 4).
|
- [pgp-ui.js](./pgp-ui.js): Settings → **Encryption keys**. Hidden on platforms without a key store (Android until Phase 4).
|
||||||
- Tests: `npm test` ([tests/pgp-keystore.test.cjs](./tests/pgp-keystore.test.cjs)).
|
- Tests: `npm test` ([tests/pgp-keystore.test.cjs](./tests/pgp-keystore.test.cjs)).
|
||||||
|
|
||||||
## 7. Phases 2–5 implementation notes
|
## 7. Phases 2–5 implementation notes
|
||||||
|
|
||||||
- [desktop/pgp-mail.cjs](./desktop/pgp-mail.cjs): detects PGP/MIME and inline PGP, decrypts, verifies signatures (inside encrypted mail, `multipart/signed` and cleartext), builds encrypted/signed PGP/MIME messages, and keeps an in-memory passphrase cache.
|
- [desktop/pgp-mail.cjs](./desktop/pgp-mail.cjs): detects PGP/MIME and inline PGP, decrypts, verifies signatures (inside encrypted mail, `multipart/signed` and cleartext), builds encrypted/signed PGP/MIME messages, and keeps an in-memory passphrase cache.
|
||||||
- [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.
|
- 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.
|
- 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).
|
||||||
- Limits: subjects and headers are not encrypted; drafts are stored unencrypted; opening encrypted attachments requires the passphrase to be remembered (see Settings → Encryption keys).
|
- Limits: subjects and headers are not encrypted; drafts are stored unencrypted; opening encrypted attachments requires the passphrase to be remembered (see Settings → Encryption keys).
|
||||||
## 8. Risks
|
## 8. Risks
|
||||||
|
|
||||||
- Android WebView performance with large attachments (may need native handling).
|
- Android WebView performance with large attachments (may need native handling).
|
||||||
- Key loss (backup flow, revocation certificate).
|
- Key loss (backup flow, revocation certificate).
|
||||||
- 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)
|
## 9. Public key servers (desktop)
|
||||||
|
|
||||||
The desktop Settings → Encryption keys view can search and publish through:
|
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.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.
|
- **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.
|
- **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.
|
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.
|
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.
|
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.
|
||||||
|
|||||||
@@ -1,42 +1,42 @@
|
|||||||
# ep-mail
|
# ep-mail
|
||||||
|
|
||||||
An Eternity Project mail client with **Eternity Daylight**, **Wasteland**, and EP themes. It includes an inbox, message reader, search, starring, snooze reminders, archive and trash actions, compose/reply/forward, contacts, and a month calendar.
|
An Eternity Project mail client with **Eternity Daylight**, **Wasteland**, and EP themes. It includes an inbox, message reader, search, starring, snooze reminders, archive and trash actions, compose/reply/forward, contacts, and a month calendar.
|
||||||
|
|
||||||
## Desktop app
|
## Desktop app
|
||||||
|
|
||||||
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 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
|
### 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.
|
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.
|
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).
|
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:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
npm install
|
npm install
|
||||||
npm run android:apk
|
npm run android:apk
|
||||||
```
|
```
|
||||||
|
|
||||||
The debug APK is written to `android/app/build/outputs/apk/debug/app-debug.apk`. Install it on a connected test device with `adb install -r android/app/build/outputs/apk/debug/app-debug.apk`, or open the project in Android Studio with `npm run android:open`. The first account enables a visible, ongoing foreground-service notification while IMAP IDLE checks for new mail; Android also runs a network-constrained periodic reconciliation. Android may delay or stop background activity after force-stop, prolonged device restrictions, or vendor battery management.
|
The debug APK is written to `android/app/build/outputs/apk/debug/app-debug.apk` and copied to `release/ep-mail <version>-debug.apk`; install it on a connected test device with `adb install -r android/app/build/outputs/apk/debug/app-debug.apk`. For a signed release, configure `EP_MAIL_ANDROID_STORE_FILE` (an absolute path), `EP_MAIL_ANDROID_STORE_PASSWORD`, `EP_MAIL_ANDROID_KEY_ALIAS`, and `EP_MAIL_ANDROID_KEY_PASSWORD` in the build environment, then run `npm run android:release-apk`. The signed artifact is copied to `release/ep-mail <version>.apk`; keep keystores and passwords out of the repository and logs. The first account enables a visible, ongoing foreground-service notification while IMAP IDLE checks for new mail; Android also runs a network-constrained periodic reconciliation. Notification previews contain generic text rather than mailbox addresses or message subjects. Android may delay or stop background activity after force-stop, prolonged device restrictions, or vendor battery management.
|
||||||
|
|
||||||
## Run on Windows or Linux
|
## Run on Windows or Linux
|
||||||
|
|
||||||
Install Python 3, open a terminal in this folder, and run:
|
Install Python 3, open a terminal in this folder, and run:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
python -m http.server 8000
|
python -m http.server 8000
|
||||||
```
|
```
|
||||||
|
|
||||||
On Windows, `py -m http.server 8000` is also available on many Python installations. Visit `http://localhost:8000` in a current browser. Use the browser's **Install app** option to add ep-mail as a standalone desktop app. The service worker caches the app shell for offline use after the first visit.
|
On Windows, `py -m http.server 8000` is also available on many Python installations. Visit `http://localhost:8000` in a current browser. Use the browser's **Install app** option to add ep-mail as a standalone desktop app. The service worker caches the app shell for offline use after the first visit.
|
||||||
|
|
||||||
## Current scope
|
## Current scope
|
||||||
|
|
||||||
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`.
|
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`.
|
||||||
|
|||||||
@@ -1,62 +1,62 @@
|
|||||||
# Security review: OpenPGP encryption
|
# Security review: OpenPGP encryption
|
||||||
|
|
||||||
Date: 2026-10-08
|
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.
|
> **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, now registered in `desktop/ipc/pgp.cjs`, plus the plaintext-send check in `desktop/ipc/mail.cjs`; the original review predates this IPC extraction.
|
- `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`, and the `window.epMailFeatures.pgp.prepareSend` feature hook used by `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.
|
||||||
|
|
||||||
## Findings
|
## Findings
|
||||||
|
|
||||||
| # | Severity | File | Issue | Confidence | Status |
|
| # | Severity | File | Issue | Confidence | Status |
|
||||||
|---|----------|------|-------|------------|--------|
|
|---|----------|------|-------|------------|--------|
|
||||||
| 1 | 🟡 MEDIUM | `pgp-mail-ui.js`, `mail-ui.js` | Encrypt-by-default is applied after a 300 ms debounced key lookup. Sending before it finished skipped the key check and sent the message unencrypted. | 9/10 | Fixed |
|
| 1 | 🟡 MEDIUM | `pgp-mail-ui.js`, `mail-ui.js` | Encrypt-by-default is applied after a 300 ms debounced key lookup. Sending before it finished skipped the key check and sent the message unencrypted. | 9/10 | Fixed |
|
||||||
| 2 | 🟡 MEDIUM | `desktop/preload.cjs`, `desktop/main.cjs`, `desktop/pgp-keystore.cjs` | A compromised renderer could add a public key for a recipient's address and call `pgp:set-trust` to mark it verified. Recipient key selection prefers higher trust, so later mail could be encrypted to the attacker's key. The confirmation existed only in the renderer UI. | 8/10 | Fixed |
|
| 2 | 🟡 MEDIUM | `desktop/preload.cjs`, `desktop/main.cjs`, `desktop/pgp-keystore.cjs` | A compromised renderer could add a public key for a recipient's address and call `pgp:set-trust` to mark it verified. Recipient key selection prefers higher trust, so later mail could be encrypted to the attacker's key. The confirmation existed only in the renderer UI. | 8/10 | Fixed |
|
||||||
|
|
||||||
No critical or high severity issues were reported.
|
No critical or high severity issues were reported.
|
||||||
|
|
||||||
## Fixes applied
|
## Fixes applied
|
||||||
|
|
||||||
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`.
|
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 at the original review time
|
## 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 recorded after the first review (2026-10-08)
|
## 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. This was still open at the time; see the later review pass below.
|
- 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)
|
## 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.
|
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 |
|
| # | 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 |
|
| 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 |
|
| 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 |
|
| 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:
|
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.
|
- #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.
|
- #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.
|
- #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
|
## Current follow-up
|
||||||
@@ -74,4 +74,4 @@ Fresh automated review of the whole repository (ep-mail 0.4.39), covering the El
|
|||||||
|---|----------|------|-------|---------------|------------|
|
|---|----------|------|-------|---------------|------------|
|
||||||
| - | - | - | - | No actionable vulnerabilities found. | - |
|
| - | - | - | - | No actionable vulnerabilities found. | - |
|
||||||
|
|
||||||
The open items under "Current follow-up" still apply: human review, dependency audit, OpenPGP.js version pinning and Android OpenPGP support.
|
The open items under "Current follow-up" still apply: human review, dependency audit, OpenPGP.js version pinning and Android OpenPGP support.
|
||||||
|
|||||||
@@ -1,78 +1,78 @@
|
|||||||
# TODO
|
# TODO
|
||||||
|
|
||||||
## Product identity
|
## Product identity
|
||||||
|
|
||||||
- [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] 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.
|
||||||
|
|
||||||
## 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 a configurable Undo Send delay 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.
|
||||||
- [x] Add attachment previews and a dedicated view to find and manage attachments across mailboxes.
|
- [x] Add attachment previews and a dedicated view to find and manage attachments across mailboxes.
|
||||||
- [x] Add configurable keyboard shortcuts for common actions such as compose, archive, reply, and search.
|
- [x] Add configurable keyboard shortcuts for common actions such as compose, archive, reply, and search.
|
||||||
- [x] Warn about suspicious sender addresses and links; require confirmation before opening external links.
|
- [x] Warn about suspicious sender addresses and links; require confirmation before opening external links.
|
||||||
- [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.
|
||||||
- [x] Block remote images by default and let users load them per message on desktop and Android/Web.
|
- [x] Block remote images by default and let users load them per message on desktop and Android/Web.
|
||||||
|
|
||||||
## Mail security
|
## Mail security
|
||||||
|
|
||||||
- [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] 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): add 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] Address findings from the automated OpenPGP security reviews (see [SECURITY_REVIEW.md](./SECURITY_REVIEW.md)).
|
- [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.
|
- [ ] 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.
|
- [ ] Add direct IPC-handler tests for both accept and cancel paths of the main-process plaintext-send confirmation.
|
||||||
- [ ] Complete the Android security work in [ANDROID_SECURITY_PLAN.md](./ANDROID_SECURITY_PLAN.md), including Android OpenPGP and release security checks.
|
- [ ] Complete the Android security work in [ANDROID_SECURITY_PLAN.md](./ANDROID_SECURITY_PLAN.md), including Android OpenPGP and release security checks.
|
||||||
|
|
||||||
## Appearance and settings
|
## Appearance and settings
|
||||||
|
|
||||||
- [ ] Fix the startup color-scheme flash so the selected dark theme is applied before the app window appears.
|
- [ ] Fix the startup color-scheme flash so the selected dark theme is applied before the app window appears.
|
||||||
- [x] Make **EP Wasteland** the default theme for new users.
|
- [x] Make **EP Wasteland** the default theme for new users.
|
||||||
- [x] Move theme selection into Settings and save the selection so the chosen theme is applied every time the program starts.
|
- [x] Move theme selection into Settings and save the selection so the chosen theme is applied every time the program starts.
|
||||||
- [x] Keep the display name in Account Settings and make it available while adding a mailbox.
|
- [x] Keep the display name in Account Settings and make it available while adding a mailbox.
|
||||||
|
|
||||||
## 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.
|
- [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.
|
||||||
- [x] Track `UIDVALIDITY`, the last processed UID, and `HIGHESTMODSEQ` per account and folder; fall back to checking message flags when mod-sequences are unavailable.
|
- [x] Track `UIDVALIDITY`, the last processed UID, and `HIGHESTMODSEQ` per account and folder; fall back to checking message flags when mod-sequences are unavailable.
|
||||||
- [x] Add persistent IMAP IDLE watchers for up to two accounts, with reconnect backoff and periodic polling as a fallback for other accounts and servers without IDLE support.
|
- [x] Add persistent IMAP IDLE watchers for up to two accounts, with reconnect backoff and periodic polling as a fallback for other accounts and servers without IDLE support.
|
||||||
- [ ] Add push mail support.
|
- [ ] Add push mail support.
|
||||||
- [x] Prevent overlapping sync runs, limit concurrent account connections, and invalidate in-flight results when an account is edited or removed.
|
- [x] Prevent overlapping sync runs, limit concurrent account connections, and invalidate in-flight results when an account is edited or removed.
|
||||||
- [x] Send updates to the renderer over IPC and show native notifications for new inbox mail.
|
- [x] Send updates to the renderer over IPC and show native notifications for new inbox mail.
|
||||||
- [x] Add new mail notifications.
|
- [x] Add new mail notifications.
|
||||||
- [x] Add an **Edit** button for each connected mail account so its account settings can be changed after setup.
|
- [x] Add an **Edit** button for each connected mail account so its account settings can be changed after setup.
|
||||||
- [x] Move CalDAV and CardDAV server configuration into Account Settings, removing the server settings controls from the Calendar and Contacts views.
|
- [x] Move CalDAV and CardDAV server configuration into Account Settings, removing the server settings controls from the Calendar and Contacts views.
|
||||||
- [x] Keep general Settings focused on appearance and other app-wide preferences rather than the display name.
|
- [x] Keep general Settings focused on appearance and other app-wide preferences rather than the display name.
|
||||||
- [x] Display name must be set per account.
|
- [x] Display name must be set per account.
|
||||||
- [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.
|
||||||
- [ ] Improve sidebar usability so all folders fit or can be reached by scrolling; consider collapsing less-used sections.
|
- [ ] Improve sidebar usability so all folders fit or can be reached by scrolling; consider collapsing less-used sections.
|
||||||
- [ ] Make labels work reliably and support creating and managing additional 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.
|
||||||
- [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 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] 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] 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.
|
- [x] Add the ability to change the passphrase of an encryption key on desktop.
|
||||||
|
|||||||
@@ -3,29 +3,29 @@ const accountMailUi = window.epMailFeatures.mail;
|
|||||||
const accountDavUi = window.epMailFeatures.dav;
|
const accountDavUi = window.epMailFeatures.dav;
|
||||||
|
|
||||||
async function openAccountManager(){
|
async function openAccountManager(){
|
||||||
const root=accountMailUi.select('#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>${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('');
|
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();accountMailUi.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{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}
|
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();accountDavUi.openManager(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)accountMailUi.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;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}
|
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){accountMailUi.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);
|
||||||
})();
|
})();
|
||||||
|
|||||||
@@ -1,101 +1,101 @@
|
|||||||
# Using Android gitignore template: https://github.com/github/gitignore/blob/HEAD/Android.gitignore
|
# Using Android gitignore template: https://github.com/github/gitignore/blob/HEAD/Android.gitignore
|
||||||
|
|
||||||
# Built application files
|
# Built application files
|
||||||
*.apk
|
*.apk
|
||||||
*.aar
|
*.aar
|
||||||
*.ap_
|
*.ap_
|
||||||
*.aab
|
*.aab
|
||||||
|
|
||||||
# Files for the ART/Dalvik VM
|
# Files for the ART/Dalvik VM
|
||||||
*.dex
|
*.dex
|
||||||
|
|
||||||
# Java class files
|
# Java class files
|
||||||
*.class
|
*.class
|
||||||
|
|
||||||
# Generated files
|
# Generated files
|
||||||
bin/
|
bin/
|
||||||
gen/
|
gen/
|
||||||
out/
|
out/
|
||||||
# Uncomment the following line in case you need and you don't have the release build type files in your app
|
# Uncomment the following line in case you need and you don't have the release build type files in your app
|
||||||
# release/
|
# release/
|
||||||
|
|
||||||
# Gradle files
|
# Gradle files
|
||||||
.gradle/
|
.gradle/
|
||||||
build/
|
build/
|
||||||
|
|
||||||
# Local configuration file (sdk path, etc)
|
# Local configuration file (sdk path, etc)
|
||||||
local.properties
|
local.properties
|
||||||
|
|
||||||
# Proguard folder generated by Eclipse
|
# Proguard folder generated by Eclipse
|
||||||
proguard/
|
proguard/
|
||||||
|
|
||||||
# Log Files
|
# Log Files
|
||||||
*.log
|
*.log
|
||||||
|
|
||||||
# Android Studio Navigation editor temp files
|
# Android Studio Navigation editor temp files
|
||||||
.navigation/
|
.navigation/
|
||||||
|
|
||||||
# Android Studio captures folder
|
# Android Studio captures folder
|
||||||
captures/
|
captures/
|
||||||
|
|
||||||
# IntelliJ
|
# IntelliJ
|
||||||
*.iml
|
*.iml
|
||||||
.idea/workspace.xml
|
.idea/workspace.xml
|
||||||
.idea/tasks.xml
|
.idea/tasks.xml
|
||||||
.idea/gradle.xml
|
.idea/gradle.xml
|
||||||
.idea/assetWizardSettings.xml
|
.idea/assetWizardSettings.xml
|
||||||
.idea/dictionaries
|
.idea/dictionaries
|
||||||
.idea/libraries
|
.idea/libraries
|
||||||
# Android Studio 3 in .gitignore file.
|
# Android Studio 3 in .gitignore file.
|
||||||
.idea/caches
|
.idea/caches
|
||||||
.idea/modules.xml
|
.idea/modules.xml
|
||||||
# Comment next line if keeping position of elements in Navigation Editor is relevant for you
|
# Comment next line if keeping position of elements in Navigation Editor is relevant for you
|
||||||
.idea/navEditor.xml
|
.idea/navEditor.xml
|
||||||
|
|
||||||
# Keystore files
|
# Keystore files
|
||||||
# Uncomment the following lines if you do not want to check your keystore files in.
|
# Uncomment the following lines if you do not want to check your keystore files in.
|
||||||
#*.jks
|
#*.jks
|
||||||
#*.keystore
|
#*.keystore
|
||||||
|
|
||||||
# External native build folder generated in Android Studio 2.2 and later
|
# External native build folder generated in Android Studio 2.2 and later
|
||||||
.externalNativeBuild
|
.externalNativeBuild
|
||||||
.cxx/
|
.cxx/
|
||||||
|
|
||||||
# Google Services (e.g. APIs or Firebase)
|
# Google Services (e.g. APIs or Firebase)
|
||||||
# google-services.json
|
# google-services.json
|
||||||
|
|
||||||
# Freeline
|
# Freeline
|
||||||
freeline.py
|
freeline.py
|
||||||
freeline/
|
freeline/
|
||||||
freeline_project_description.json
|
freeline_project_description.json
|
||||||
|
|
||||||
# fastlane
|
# fastlane
|
||||||
fastlane/report.xml
|
fastlane/report.xml
|
||||||
fastlane/Preview.html
|
fastlane/Preview.html
|
||||||
fastlane/screenshots
|
fastlane/screenshots
|
||||||
fastlane/test_output
|
fastlane/test_output
|
||||||
fastlane/readme.md
|
fastlane/readme.md
|
||||||
|
|
||||||
# Version control
|
# Version control
|
||||||
vcs.xml
|
vcs.xml
|
||||||
|
|
||||||
# lint
|
# lint
|
||||||
lint/intermediates/
|
lint/intermediates/
|
||||||
lint/generated/
|
lint/generated/
|
||||||
lint/outputs/
|
lint/outputs/
|
||||||
lint/tmp/
|
lint/tmp/
|
||||||
# lint/reports/
|
# lint/reports/
|
||||||
|
|
||||||
# Android Profiling
|
# Android Profiling
|
||||||
*.hprof
|
*.hprof
|
||||||
|
|
||||||
# Cordova plugins for Capacitor
|
# Cordova plugins for Capacitor
|
||||||
capacitor-cordova-android-plugins
|
capacitor-cordova-android-plugins
|
||||||
|
|
||||||
# Copied web assets
|
# Copied web assets
|
||||||
app/src/main/assets/public
|
app/src/main/assets/public
|
||||||
|
|
||||||
# Generated Config files
|
# Generated Config files
|
||||||
app/src/main/assets/capacitor.config.json
|
app/src/main/assets/capacitor.config.json
|
||||||
app/src/main/assets/capacitor.plugins.json
|
app/src/main/assets/capacitor.plugins.json
|
||||||
app/src/main/res/xml/config.xml
|
app/src/main/res/xml/config.xml
|
||||||
|
|||||||
@@ -1,2 +1,2 @@
|
|||||||
/build/*
|
/build/*
|
||||||
!/build/.npmkeep
|
!/build/.npmkeep
|
||||||
|
|||||||
@@ -1,78 +1,103 @@
|
|||||||
apply plugin: 'com.android.application'
|
apply plugin: 'com.android.application'
|
||||||
apply plugin: 'org.jetbrains.kotlin.android'
|
apply plugin: 'org.jetbrains.kotlin.android'
|
||||||
|
|
||||||
def appVersion = new groovy.json.JsonSlurper().parse(file("../../package.json")).version
|
def appVersion = new groovy.json.JsonSlurper().parse(file("../../package.json")).version
|
||||||
def appVersionParts = appVersion.tokenize('.').collect { it.toInteger() }
|
def appVersionParts = appVersion.tokenize('.').collect { it.toInteger() }
|
||||||
|
def releaseStoreFile = System.getenv('EP_MAIL_ANDROID_STORE_FILE')
|
||||||
|
def releaseStorePassword = System.getenv('EP_MAIL_ANDROID_STORE_PASSWORD')
|
||||||
|
def releaseKeyAlias = System.getenv('EP_MAIL_ANDROID_KEY_ALIAS')
|
||||||
|
def releaseKeyPassword = System.getenv('EP_MAIL_ANDROID_KEY_PASSWORD')
|
||||||
|
def releaseSigningValues = [releaseStoreFile, releaseStorePassword, releaseKeyAlias, releaseKeyPassword]
|
||||||
|
def hasAnyReleaseSigningValue = releaseSigningValues.any { it != null && !it.isBlank() }
|
||||||
|
def hasCompleteReleaseSigning = releaseSigningValues.every { it != null && !it.isBlank() }
|
||||||
|
|
||||||
android {
|
if (hasAnyReleaseSigningValue && !hasCompleteReleaseSigning) {
|
||||||
namespace = "studio.daybreak.mail"
|
throw new GradleException('Android release signing requires EP_MAIL_ANDROID_STORE_FILE, EP_MAIL_ANDROID_STORE_PASSWORD, EP_MAIL_ANDROID_KEY_ALIAS, and EP_MAIL_ANDROID_KEY_PASSWORD.')
|
||||||
compileSdk = rootProject.ext.compileSdkVersion
|
}
|
||||||
|
if (hasCompleteReleaseSigning && !new File(releaseStoreFile).isAbsolute()) {
|
||||||
|
throw new GradleException('EP_MAIL_ANDROID_STORE_FILE must be an absolute path.')
|
||||||
|
}
|
||||||
|
|
||||||
|
android {
|
||||||
|
namespace = "studio.daybreak.mail"
|
||||||
|
compileSdk = rootProject.ext.compileSdkVersion
|
||||||
buildFeatures {
|
buildFeatures {
|
||||||
buildConfig true
|
buildConfig true
|
||||||
}
|
}
|
||||||
packaging {
|
if (hasCompleteReleaseSigning) {
|
||||||
resources {
|
signingConfigs {
|
||||||
pickFirsts += "META-INF/NOTICE.md"
|
release {
|
||||||
pickFirsts += "META-INF/LICENSE.md"
|
storeFile file(releaseStoreFile)
|
||||||
|
storePassword releaseStorePassword
|
||||||
|
keyAlias releaseKeyAlias
|
||||||
|
keyPassword releaseKeyPassword
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
defaultConfig {
|
packaging {
|
||||||
applicationId "studio.daybreak.mail"
|
resources {
|
||||||
minSdkVersion rootProject.ext.minSdkVersion
|
pickFirsts += "META-INF/NOTICE.md"
|
||||||
targetSdkVersion rootProject.ext.targetSdkVersion
|
pickFirsts += "META-INF/LICENSE.md"
|
||||||
versionCode appVersionParts[0] * 10000 + appVersionParts[1] * 100 + appVersionParts[2]
|
}
|
||||||
versionName appVersion
|
}
|
||||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
defaultConfig {
|
||||||
aaptOptions {
|
applicationId "studio.daybreak.mail"
|
||||||
// Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.
|
minSdkVersion rootProject.ext.minSdkVersion
|
||||||
// Default: https://android.googlesource.com/platform/frameworks/base/+/282e181b58cf72b6ca770dc7ca5f91f135444502/tools/aapt/AaptAssets.cpp#61
|
targetSdkVersion rootProject.ext.targetSdkVersion
|
||||||
ignoreAssetsPattern = '!.svn:!.git:!.ds_store:!*.scc:.*:!CVS:!thumbs.db:!picasa.ini:!*~'
|
versionCode appVersionParts[0] * 10000 + appVersionParts[1] * 100 + appVersionParts[2]
|
||||||
}
|
versionName appVersion
|
||||||
}
|
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||||
buildTypes {
|
aaptOptions {
|
||||||
|
// Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.
|
||||||
|
// Default: https://android.googlesource.com/platform/frameworks/base/+/282e181b58cf72b6ca770dc7ca5f91f135444502/tools/aapt/AaptAssets.cpp#61
|
||||||
|
ignoreAssetsPattern = '!.svn:!.git:!.ds_store:!*.scc:.*:!CVS:!thumbs.db:!picasa.ini:!*~'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
buildTypes {
|
||||||
release {
|
release {
|
||||||
minifyEnabled false
|
minifyEnabled false
|
||||||
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
|
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
|
||||||
|
if (hasCompleteReleaseSigning) signingConfig signingConfigs.release
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
compileOptions {
|
compileOptions {
|
||||||
sourceCompatibility JavaVersion.VERSION_21
|
sourceCompatibility JavaVersion.VERSION_21
|
||||||
targetCompatibility JavaVersion.VERSION_21
|
targetCompatibility JavaVersion.VERSION_21
|
||||||
}
|
}
|
||||||
kotlinOptions {
|
kotlinOptions {
|
||||||
jvmTarget = '21'
|
jvmTarget = '21'
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
repositories {
|
repositories {
|
||||||
flatDir{
|
flatDir{
|
||||||
dirs '../capacitor-cordova-android-plugins/src/main/libs', 'libs'
|
dirs '../capacitor-cordova-android-plugins/src/main/libs', 'libs'
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
implementation fileTree(include: ['*.jar'], dir: 'libs')
|
implementation fileTree(include: ['*.jar'], dir: 'libs')
|
||||||
implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion"
|
implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion"
|
||||||
implementation "androidx.coordinatorlayout:coordinatorlayout:$androidxCoordinatorLayoutVersion"
|
implementation "androidx.coordinatorlayout:coordinatorlayout:$androidxCoordinatorLayoutVersion"
|
||||||
implementation "androidx.core:core-splashscreen:$coreSplashScreenVersion"
|
implementation "androidx.core:core-splashscreen:$coreSplashScreenVersion"
|
||||||
implementation project(':capacitor-android')
|
implementation project(':capacitor-android')
|
||||||
implementation 'com.sun.mail:android-mail:1.6.7'
|
implementation 'com.sun.mail:android-mail:1.6.7'
|
||||||
implementation 'com.sun.mail:android-activation:1.6.7'
|
implementation 'com.sun.mail:android-activation:1.6.7'
|
||||||
implementation 'com.squareup.okhttp3:okhttp:4.12.0'
|
implementation 'com.squareup.okhttp3:okhttp:4.12.0'
|
||||||
implementation 'androidx.work:work-runtime-ktx:2.10.1'
|
implementation 'androidx.work:work-runtime-ktx:2.10.1'
|
||||||
testImplementation "junit:junit:$junitVersion"
|
testImplementation "junit:junit:$junitVersion"
|
||||||
androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion"
|
androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion"
|
||||||
androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion"
|
androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion"
|
||||||
implementation project(':capacitor-cordova-android-plugins')
|
implementation project(':capacitor-cordova-android-plugins')
|
||||||
}
|
}
|
||||||
|
|
||||||
apply from: 'capacitor.build.gradle'
|
apply from: 'capacitor.build.gradle'
|
||||||
|
|
||||||
try {
|
try {
|
||||||
def servicesJSON = file('google-services.json')
|
def servicesJSON = file('google-services.json')
|
||||||
if (servicesJSON.text) {
|
if (servicesJSON.text) {
|
||||||
apply plugin: 'com.google.gms.google-services'
|
apply plugin: 'com.google.gms.google-services'
|
||||||
}
|
}
|
||||||
} catch(Exception e) {
|
} catch(Exception e) {
|
||||||
logger.info("google-services.json not found, google-services plugin not applied. Push Notifications won't work")
|
logger.info("google-services.json not found, google-services plugin not applied. Push Notifications won't work")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,21 +1,21 @@
|
|||||||
# Add project specific ProGuard rules here.
|
# Add project specific ProGuard rules here.
|
||||||
# You can control the set of applied configuration files using the
|
# You can control the set of applied configuration files using the
|
||||||
# proguardFiles setting in build.gradle.
|
# proguardFiles setting in build.gradle.
|
||||||
#
|
#
|
||||||
# For more details, see
|
# For more details, see
|
||||||
# http://developer.android.com/guide/developing/tools/proguard.html
|
# http://developer.android.com/guide/developing/tools/proguard.html
|
||||||
|
|
||||||
# If your project uses WebView with JS, uncomment the following
|
# If your project uses WebView with JS, uncomment the following
|
||||||
# and specify the fully qualified class name to the JavaScript interface
|
# and specify the fully qualified class name to the JavaScript interface
|
||||||
# class:
|
# class:
|
||||||
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
|
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
|
||||||
# public *;
|
# public *;
|
||||||
#}
|
#}
|
||||||
|
|
||||||
# Uncomment this to preserve the line number information for
|
# Uncomment this to preserve the line number information for
|
||||||
# debugging stack traces.
|
# debugging stack traces.
|
||||||
#-keepattributes SourceFile,LineNumberTable
|
#-keepattributes SourceFile,LineNumberTable
|
||||||
|
|
||||||
# If you keep the line number information, uncomment this to
|
# If you keep the line number information, uncomment this to
|
||||||
# hide the original source file name.
|
# hide the original source file name.
|
||||||
#-renamesourcefileattribute SourceFile
|
#-renamesourcefileattribute SourceFile
|
||||||
|
|||||||
@@ -1,26 +1,26 @@
|
|||||||
package com.getcapacitor.myapp;
|
package com.getcapacitor.myapp;
|
||||||
|
|
||||||
import static org.junit.Assert.*;
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
import android.content.Context;
|
import android.content.Context;
|
||||||
import androidx.test.ext.junit.runners.AndroidJUnit4;
|
import androidx.test.ext.junit.runners.AndroidJUnit4;
|
||||||
import androidx.test.platform.app.InstrumentationRegistry;
|
import androidx.test.platform.app.InstrumentationRegistry;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.junit.runner.RunWith;
|
import org.junit.runner.RunWith;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Instrumented test, which will execute on an Android device.
|
* Instrumented test, which will execute on an Android device.
|
||||||
*
|
*
|
||||||
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
|
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
|
||||||
*/
|
*/
|
||||||
@RunWith(AndroidJUnit4.class)
|
@RunWith(AndroidJUnit4.class)
|
||||||
public class ExampleInstrumentedTest {
|
public class ExampleInstrumentedTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void useAppContext() throws Exception {
|
public void useAppContext() throws Exception {
|
||||||
// Context of the app under test.
|
// Context of the app under test.
|
||||||
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
|
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
|
||||||
|
|
||||||
assertEquals("com.getcapacitor.app", appContext.getPackageName());
|
assertEquals("com.getcapacitor.app", appContext.getPackageName());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,48 +1,41 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
|
||||||
<uses-permission android:name="android.permission.INTERNET" />
|
<uses-permission android:name="android.permission.INTERNET" />
|
||||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
|
||||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||||
|
|
||||||
<application
|
<application
|
||||||
android:allowBackup="false"
|
android:allowBackup="false"
|
||||||
android:icon="@mipmap/ic_launcher"
|
android:dataExtractionRules="@xml/data_extraction_rules"
|
||||||
android:label="@string/app_name"
|
android:usesCleartextTraffic="false"
|
||||||
android:roundIcon="@mipmap/ic_launcher_round"
|
android:icon="@mipmap/ic_launcher"
|
||||||
android:supportsRtl="true"
|
android:label="@string/app_name"
|
||||||
android:theme="@style/AppTheme">
|
android:roundIcon="@mipmap/ic_launcher_round"
|
||||||
|
android:supportsRtl="true"
|
||||||
<activity
|
android:theme="@style/AppTheme">
|
||||||
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode|navigation|density"
|
|
||||||
android:name=".MainActivity"
|
<activity
|
||||||
android:label="@string/title_activity_main"
|
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode|navigation|density"
|
||||||
android:theme="@style/AppTheme.NoActionBarLaunch"
|
android:name=".MainActivity"
|
||||||
android:launchMode="singleTask"
|
android:label="@string/title_activity_main"
|
||||||
android:exported="true">
|
android:theme="@style/AppTheme.NoActionBarLaunch"
|
||||||
|
android:launchMode="singleTask"
|
||||||
<intent-filter>
|
android:exported="true">
|
||||||
<action android:name="android.intent.action.MAIN" />
|
|
||||||
<category android:name="android.intent.category.LAUNCHER" />
|
<intent-filter>
|
||||||
</intent-filter>
|
<action android:name="android.intent.action.MAIN" />
|
||||||
|
<category android:name="android.intent.category.LAUNCHER" />
|
||||||
</activity>
|
</intent-filter>
|
||||||
|
|
||||||
<service
|
</activity>
|
||||||
android:name=".MailIdleService"
|
|
||||||
android:exported="false"
|
<service
|
||||||
android:foregroundServiceType="dataSync" />
|
android:name=".MailIdleService"
|
||||||
|
android:exported="false"
|
||||||
<provider
|
android:foregroundServiceType="dataSync" />
|
||||||
android:name="androidx.core.content.FileProvider"
|
|
||||||
android:authorities="${applicationId}.fileprovider"
|
</application>
|
||||||
android:exported="false"
|
|
||||||
android:grantUriPermissions="true">
|
</manifest>
|
||||||
<meta-data
|
|
||||||
android:name="android.support.FILE_PROVIDER_PATHS"
|
|
||||||
android:resource="@xml/file_paths"></meta-data>
|
|
||||||
</provider>
|
|
||||||
</application>
|
|
||||||
|
|
||||||
</manifest>
|
|
||||||
|
|||||||
@@ -1,443 +1,437 @@
|
|||||||
package studio.daybreak.mail
|
package studio.daybreak.mail
|
||||||
|
|
||||||
import android.util.Base64
|
import android.util.Base64
|
||||||
import org.json.JSONArray
|
import org.json.JSONArray
|
||||||
import org.json.JSONObject
|
import org.json.JSONObject
|
||||||
import org.w3c.dom.Element
|
import org.w3c.dom.Element
|
||||||
import java.io.ByteArrayInputStream
|
import java.io.ByteArrayInputStream
|
||||||
import java.net.URL
|
import java.net.URL
|
||||||
import java.nio.charset.StandardCharsets
|
import java.nio.charset.StandardCharsets
|
||||||
import java.util.Locale
|
import java.util.Locale
|
||||||
import java.util.UUID
|
import java.util.UUID
|
||||||
import okhttp3.OkHttpClient
|
import okhttp3.OkHttpClient
|
||||||
import okhttp3.Request
|
import okhttp3.Request
|
||||||
import okhttp3.MediaType.Companion.toMediaTypeOrNull
|
import okhttp3.MediaType.Companion.toMediaTypeOrNull
|
||||||
import okhttp3.RequestBody.Companion.toRequestBody
|
import okhttp3.RequestBody.Companion.toRequestBody
|
||||||
import java.util.concurrent.TimeUnit
|
import java.util.concurrent.TimeUnit
|
||||||
import javax.xml.parsers.DocumentBuilderFactory
|
import javax.xml.parsers.DocumentBuilderFactory
|
||||||
|
|
||||||
internal object AndroidDavService {
|
internal object AndroidDavService {
|
||||||
private val httpClient = OkHttpClient.Builder()
|
private val httpClient = OkHttpClient.Builder()
|
||||||
.connectTimeout(20, TimeUnit.SECONDS)
|
.connectTimeout(20, TimeUnit.SECONDS)
|
||||||
.readTimeout(30, TimeUnit.SECONDS)
|
.readTimeout(30, TimeUnit.SECONDS)
|
||||||
|
.followRedirects(false)
|
||||||
|
.followSslRedirects(false)
|
||||||
.build()
|
.build()
|
||||||
|
|
||||||
fun list(): JSONObject {
|
fun list(): JSONObject {
|
||||||
val store = AndroidAccountVault.read()
|
val store = AndroidAccountVault.read()
|
||||||
return JSONObject()
|
return JSONObject()
|
||||||
.put("caldav", AndroidAccountVault.publicDavAccounts("caldav"))
|
.put("caldav", AndroidAccountVault.publicDavAccounts("caldav"))
|
||||||
.put("carddav", AndroidAccountVault.publicDavAccounts("carddav"))
|
.put("carddav", AndroidAccountVault.publicDavAccounts("carddav"))
|
||||||
.put("activeCaldavId", store.optString("activeCaldavId"))
|
.put("activeCaldavId", store.optString("activeCaldavId"))
|
||||||
.put("activeCarddavId", store.optString("activeCarddavId"))
|
.put("activeCarddavId", store.optString("activeCarddavId"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fun connect(input: JSONObject): JSONObject {
|
||||||
|
val type = type(input.optString("type"))
|
||||||
|
val serverUrl = input.optString("serverUrl").trim()
|
||||||
|
val username = input.optString("username").trim()
|
||||||
|
val password = input.optString("password")
|
||||||
|
val url = DavUrlPolicy.parseServerUrl(serverUrl)
|
||||||
|
require(username.isNotBlank() && password.isNotBlank()) { "Enter the DAV username and password." }
|
||||||
|
val collections = discoverCollections(url.toString(), username, password, type)
|
||||||
|
require(collections.length() > 0) {
|
||||||
|
"No ${if (type == "caldav") "calendars" else "address books"} were found on this server."
|
||||||
|
}
|
||||||
|
val account = JSONObject()
|
||||||
|
.put("id", UUID.randomUUID().toString())
|
||||||
|
.put("type", type)
|
||||||
|
.put("serverUrl", url.toString())
|
||||||
|
.put("username", username)
|
||||||
|
.put("password", password)
|
||||||
|
.put("collections", collections)
|
||||||
|
val saved = AndroidAccountVault.putDavAccount(type, account)
|
||||||
|
val publicConfig = publicDav(saved)
|
||||||
|
return JSONObject()
|
||||||
|
.put("config", publicConfig)
|
||||||
|
.put("collections", collections)
|
||||||
|
.put("accounts", list())
|
||||||
|
}
|
||||||
|
|
||||||
|
fun activate(typeInput: String, id: String): JSONObject {
|
||||||
|
val type = type(typeInput)
|
||||||
|
val config = AndroidAccountVault.activeDav(type, id)
|
||||||
|
?: throw IllegalStateException("That DAV account could not be found.")
|
||||||
|
val store = AndroidAccountVault.read()
|
||||||
|
store.put(if (type == "caldav") "activeCaldavId" else "activeCarddavId", config.optString("id"))
|
||||||
|
AndroidAccountVault.write(store)
|
||||||
|
return JSONObject().put("id", config.optString("id"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fun remove(typeInput: String, id: String): JSONObject =
|
||||||
|
AndroidAccountVault.removeDavAccount(type(typeInput), id)
|
||||||
|
|
||||||
|
fun sync(typeInput: String): JSONObject {
|
||||||
|
val type = type(typeInput)
|
||||||
|
val account = AndroidAccountVault.activeDav(type)
|
||||||
|
?: throw IllegalStateException("Connect a ${if (type == "caldav") "CalDAV" else "CardDAV"} server first.")
|
||||||
|
val collectionKey = if (type == "caldav") "calendar" else "addressbook"
|
||||||
|
val result = JSONArray()
|
||||||
|
val collections = account.optJSONArray("collections") ?: JSONArray()
|
||||||
|
for (index in 0 until collections.length()) {
|
||||||
|
val collection = collections.getJSONObject(index)
|
||||||
|
val objects = listObjects(account, collection, type)
|
||||||
|
for (obj in objects) {
|
||||||
|
val href = obj.optString("href")
|
||||||
|
val data = obj.optString("data")
|
||||||
|
if (data.isBlank()) continue
|
||||||
|
if (type == "caldav") parseCalendar(data, account, collection, obj).forEach(result::put)
|
||||||
|
else parseContacts(data, account, collection, obj).forEach(result::put)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return JSONObject().put("items", result).put("account", publicDav(account))
|
||||||
|
.put("collectionType", collectionKey)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun saveEvent(input: JSONObject): JSONObject? {
|
||||||
|
val remote = input.optJSONObject("_dav") ?: JSONObject()
|
||||||
|
val account = AndroidAccountVault.activeDav("caldav", remote.optString("accountId").ifBlank { null }) ?: return null
|
||||||
|
val collections = account.optJSONArray("collections") ?: JSONArray()
|
||||||
|
val collection = findCollection(collections, remote.optString("collectionUrl"))
|
||||||
|
?: throw IllegalStateException("No writable calendar was found.")
|
||||||
|
val uid = remote.optString("uid").ifBlank { UUID.randomUUID().toString() }
|
||||||
|
val filename = "$uid.ics"
|
||||||
|
val collectionUrl = collection.optString("url")
|
||||||
|
val target = remote.optString("objectUrl").ifBlank { collectionUrl.trimEnd('/') + "/" + filename }
|
||||||
|
val data = calendarData(input, uid)
|
||||||
|
val response = request(account, target, "PUT", data, mapOf("Content-Type" to "text/calendar; charset=utf-8"))
|
||||||
|
require(response.code in 200..299) { "The calendar server rejected the event (${response.code})." }
|
||||||
|
return JSONObject()
|
||||||
|
.put("accountId", account.optString("id"))
|
||||||
|
.put("collectionUrl", collectionUrl)
|
||||||
|
.put("objectUrl", target)
|
||||||
|
.put("etag", response.headers["etag"] ?: remote.optString("etag"))
|
||||||
|
.put("uid", uid)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun deleteEvent(remote: JSONObject) {
|
||||||
|
val account = AndroidAccountVault.activeDav("caldav", remote.optString("accountId"))
|
||||||
|
?: throw IllegalStateException("That calendar account could not be found.")
|
||||||
|
val url = remote.optString("objectUrl")
|
||||||
|
if (url.isBlank()) return
|
||||||
|
val response = request(account, url, "DELETE", null)
|
||||||
|
require(response.code in 200..299 || response.code == 404) { "The calendar server rejected the deletion (${response.code})." }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun saveContact(input: JSONObject): JSONObject? {
|
||||||
|
val remote = input.optJSONObject("_dav") ?: JSONObject()
|
||||||
|
val account = AndroidAccountVault.activeDav("carddav", remote.optString("accountId").ifBlank { null }) ?: return null
|
||||||
|
val collections = account.optJSONArray("collections") ?: JSONArray()
|
||||||
|
val collection = findCollection(collections, remote.optString("collectionUrl"))
|
||||||
|
?: throw IllegalStateException("No writable address book was found.")
|
||||||
|
val uid = remote.optString("uid").ifBlank { UUID.randomUUID().toString() }
|
||||||
|
val filename = "$uid.vcf"
|
||||||
|
val collectionUrl = collection.optString("url")
|
||||||
|
val target = remote.optString("objectUrl").ifBlank { collectionUrl.trimEnd('/') + "/" + filename }
|
||||||
|
val response = request(account, target, "PUT", vcardData(input, uid), mapOf("Content-Type" to "text/vcard; charset=utf-8"))
|
||||||
|
require(response.code in 200..299) { "The address book server rejected the contact (${response.code})." }
|
||||||
|
return JSONObject()
|
||||||
|
.put("accountId", account.optString("id"))
|
||||||
|
.put("collectionUrl", collectionUrl)
|
||||||
|
.put("objectUrl", target)
|
||||||
|
.put("etag", response.headers["etag"] ?: remote.optString("etag"))
|
||||||
|
.put("uid", uid)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun deleteContact(remote: JSONObject) {
|
||||||
|
val account = AndroidAccountVault.activeDav("carddav", remote.optString("accountId"))
|
||||||
|
?: throw IllegalStateException("That address book account could not be found.")
|
||||||
|
val url = remote.optString("objectUrl")
|
||||||
|
if (url.isBlank()) return
|
||||||
|
val response = request(account, url, "DELETE", null)
|
||||||
|
require(response.code in 200..299 || response.code == 404) { "The address book server rejected the deletion (${response.code})." }
|
||||||
|
}
|
||||||
|
|
||||||
|
private data class HttpResult(val code: Int, val body: ByteArray, val headers: Map<String, String>)
|
||||||
|
|
||||||
|
private fun request(
|
||||||
|
account: JSONObject,
|
||||||
|
address: String,
|
||||||
|
method: String,
|
||||||
|
body: String?,
|
||||||
|
headers: Map<String, String> = emptyMap()
|
||||||
|
): HttpResult {
|
||||||
|
DavUrlPolicy.requireSameOrigin(account.optString("serverUrl"), address)
|
||||||
|
val requestBody = body?.toRequestBody(headers["Content-Type"]?.toMediaTypeOrNull())
|
||||||
|
val builder = Request.Builder()
|
||||||
|
.url(address)
|
||||||
|
.header("Authorization", basicAuth(account))
|
||||||
|
.header("User-Agent", "ep-mail-Android")
|
||||||
|
for ((key, value) in headers) builder.header(key, value)
|
||||||
|
builder.method(method, requestBody)
|
||||||
|
httpClient.newCall(builder.build()).execute().use { response ->
|
||||||
|
val bytes = response.body?.bytes() ?: ByteArray(0)
|
||||||
|
val responseHeaders = response.headers.toMultimap().mapValues { (_, values) -> values.firstOrNull().orEmpty() }
|
||||||
|
return HttpResult(response.code, bytes, responseHeaders)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun discoverCollections(serverUrl: String, username: String, password: String, type: String): JSONArray {
|
||||||
|
val base = JSONObject().put("serverUrl", serverUrl).put("username", username).put("password", password)
|
||||||
|
val setName = if (type == "caldav") "calendar-home-set" else "addressbook-home-set"
|
||||||
|
val rootResponse = request(base, serverUrl, "PROPFIND", propfindBody(setName), mapOf(
|
||||||
|
"Depth" to "0",
|
||||||
|
"Content-Type" to "application/xml; charset=utf-8"
|
||||||
|
))
|
||||||
|
require(rootResponse.code in 200..299 || rootResponse.code == 207) {
|
||||||
|
"Could not access the DAV server (${rootResponse.code})."
|
||||||
|
}
|
||||||
|
val rootDocument = parseXml(rootResponse.body)
|
||||||
|
var homeUrl = findHref(rootDocument, setName)?.let { resolveUrl(serverUrl, it) }
|
||||||
|
if (homeUrl == null) {
|
||||||
|
val principal = findHref(rootDocument, "current-user-principal")
|
||||||
|
if (principal != null) {
|
||||||
|
val principalUrl = resolveUrl(serverUrl, principal)
|
||||||
|
val principalResponse = request(base, principalUrl, "PROPFIND", propfindBody(setName), mapOf(
|
||||||
|
"Depth" to "0",
|
||||||
|
"Content-Type" to "application/xml; charset=utf-8"
|
||||||
|
))
|
||||||
|
if (principalResponse.code in 200..299 || principalResponse.code == 207) {
|
||||||
|
homeUrl = findHref(parseXml(principalResponse.body), setName)?.let { resolveUrl(principalUrl, it) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val collectionUrl = homeUrl ?: serverUrl
|
||||||
|
val response = request(base, collectionUrl, "PROPFIND", collectionBody(), mapOf(
|
||||||
|
"Depth" to "1",
|
||||||
|
"Content-Type" to "application/xml; charset=utf-8"
|
||||||
|
))
|
||||||
|
require(response.code in 200..299 || response.code == 207) {
|
||||||
|
"Could not discover DAV collections (${response.code})."
|
||||||
|
}
|
||||||
|
val document = parseXml(response.body)
|
||||||
|
val requiredType = if (type == "caldav") "calendar" else "addressbook"
|
||||||
|
val result = JSONArray()
|
||||||
|
val responses = document.getElementsByTagNameNS("*", "response")
|
||||||
|
for (index in 0 until responses.length) {
|
||||||
|
val responseElement = responses.item(index) as? Element ?: continue
|
||||||
|
val href = childText(responseElement, "href") ?: continue
|
||||||
|
if (responseElement.getElementsByTagNameNS("*", requiredType).length == 0) continue
|
||||||
|
val resolved = resolveUrl(collectionUrl, href)
|
||||||
|
val displayName = textContent(responseElement, "displayname").orEmpty().ifBlank { resolved }
|
||||||
|
result.put(JSONObject().put("url", resolved).put("name", displayName))
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun listObjects(account: JSONObject, collection: JSONObject, type: String): List<JSONObject> {
|
||||||
|
val collectionUrl = collection.optString("url")
|
||||||
|
val response = request(account, collectionUrl, "PROPFIND", collectionBody(), mapOf(
|
||||||
|
"Depth" to "1",
|
||||||
|
"Content-Type" to "application/xml; charset=utf-8"
|
||||||
|
))
|
||||||
|
require(response.code in 200..299 || response.code == 207) {
|
||||||
|
"Could not read DAV collection ${collection.optString("name")} (${response.code})."
|
||||||
|
}
|
||||||
|
val document = parseXml(response.body)
|
||||||
|
val responses = document.getElementsByTagNameNS("*", "response")
|
||||||
|
val result = ArrayList<JSONObject>()
|
||||||
|
for (index in 0 until responses.length) {
|
||||||
|
val element = responses.item(index) as? Element ?: continue
|
||||||
|
val href = childText(element, "href") ?: continue
|
||||||
|
val objectUrl = resolveUrl(collectionUrl, href)
|
||||||
|
if (objectUrl.trimEnd('/') == collectionUrl.trimEnd('/')) continue
|
||||||
|
val data = if (type == "caldav") textContent(element, "calendar-data") else textContent(element, "address-data")
|
||||||
|
val content = if (!data.isNullOrBlank()) data else {
|
||||||
|
val fetched = request(account, objectUrl, "GET", null)
|
||||||
|
if (fetched.code !in 200..299) continue
|
||||||
|
String(fetched.body, StandardCharsets.UTF_8)
|
||||||
|
}
|
||||||
|
result.add(JSONObject()
|
||||||
|
.put("href", objectUrl)
|
||||||
|
.put("etag", textContent(element, "getetag").orEmpty())
|
||||||
|
.put("data", content))
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun parseCalendar(data: String, account: JSONObject, collection: JSONObject, resource: JSONObject): List<JSONObject> {
|
||||||
|
val unfolded = unfold(data)
|
||||||
|
return Regex("BEGIN:VEVENT(.*?)END:VEVENT", setOf(RegexOption.IGNORE_CASE, RegexOption.DOT_MATCHES_ALL))
|
||||||
|
.findAll(unfolded).mapNotNull { match ->
|
||||||
|
val block = match.groupValues[1]
|
||||||
|
val fields = parseProperties(block)
|
||||||
|
val uid = fields["UID"].orEmpty().ifBlank { UUID.randomUUID().toString() }
|
||||||
|
val (date, time) = parseDate(fields["DTSTART"].orEmpty()) ?: return@mapNotNull null
|
||||||
|
JSONObject()
|
||||||
|
.put("id", "dav:${account.optString("id")}:${encode(resource.optString("href"))}:${encode(uid)}")
|
||||||
|
.put("title", unescape(fields["SUMMARY"].orEmpty()).ifBlank { "(no title)" })
|
||||||
|
.put("date", date)
|
||||||
|
.put("time", time)
|
||||||
|
.put("with", Regex("(?im)^ATTENDEE[^:]*:(?:mailto:)?([^\\r\\n]+)").findAll(block)
|
||||||
|
.map { it.groupValues[1].trim() }.joinToString(", "))
|
||||||
|
.put("place", unescape(fields["LOCATION"].orEmpty()))
|
||||||
|
.put("notes", unescape(fields["DESCRIPTION"].orEmpty()))
|
||||||
|
.put("_dav", JSONObject()
|
||||||
|
.put("accountId", account.optString("id"))
|
||||||
|
.put("collectionUrl", collection.optString("url"))
|
||||||
|
.put("objectUrl", resource.optString("href"))
|
||||||
|
.put("etag", resource.optString("etag"))
|
||||||
|
.put("uid", uid))
|
||||||
|
}.toList()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun parseContacts(data: String, account: JSONObject, collection: JSONObject, resource: JSONObject): List<JSONObject> {
|
||||||
|
val cards = Regex("BEGIN:VCARD(.*?)END:VCARD", setOf(RegexOption.IGNORE_CASE, RegexOption.DOT_MATCHES_ALL))
|
||||||
|
return cards.findAll(unfold(data)).mapNotNull { match ->
|
||||||
|
val block = match.groupValues[1]
|
||||||
|
val fields = parseProperties(block)
|
||||||
|
val name = unescape(fields["FN"].orEmpty()).trim()
|
||||||
|
if (name.isBlank()) return@mapNotNull null
|
||||||
|
val uid = fields["UID"].orEmpty()
|
||||||
|
JSONObject()
|
||||||
|
.put("id", "dav:${account.optString("id")}:${encode(resource.optString("href"))}:${encode(uid)}")
|
||||||
|
.put("name", name)
|
||||||
|
.put("email", unescape(fields["EMAIL"].orEmpty()))
|
||||||
|
.put("note", unescape(fields["NOTE"].orEmpty()))
|
||||||
|
.put("initials", name.split(Regex("\\s+")).mapNotNull { it.firstOrNull()?.toString() }
|
||||||
|
.joinToString("").take(2).uppercase(Locale.getDefault()))
|
||||||
|
.put("color", "#dce9dd")
|
||||||
|
.put("_dav", JSONObject()
|
||||||
|
.put("accountId", account.optString("id"))
|
||||||
|
.put("collectionUrl", collection.optString("url"))
|
||||||
|
.put("objectUrl", resource.optString("href"))
|
||||||
|
.put("etag", resource.optString("etag"))
|
||||||
|
.put("uid", uid))
|
||||||
|
}.toList()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun calendarData(event: JSONObject, uid: String): String {
|
||||||
|
val date = event.optString("date").replace("-", "")
|
||||||
|
val time = event.optString("time")
|
||||||
|
val start = if (time.isBlank()) "DTSTART;VALUE=DATE:$date" else "DTSTART;TZID=UTC:${date}T${time.replace(":", "")}00"
|
||||||
|
val end = if (time.isBlank()) "" else {
|
||||||
|
val parts = time.split(":")
|
||||||
|
val mins = (parts.getOrNull(0)?.toIntOrNull() ?: 0) * 60 + (parts.getOrNull(1)?.toIntOrNull() ?: 0) + 60
|
||||||
|
val endTime = "%04d%02d00".format(Locale.ROOT, (mins / 60) % 24, mins % 60)
|
||||||
|
"DTEND;TZID=UTC:${date}T$endTime\r\n"
|
||||||
|
}
|
||||||
|
return "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Eternity Project//ep-mail CalDAV\r\nBEGIN:VEVENT\r\nUID:${escape(uid)}\r\nDTSTAMP:${utcNow()}\r\n$start\r\n$end${property("SUMMARY", event.optString("title"))}${property("LOCATION", event.optString("place"))}${property("DESCRIPTION", event.optString("notes"))}END:VEVENT\r\nEND:VCALENDAR\r\n"
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun vcardData(contact: JSONObject, uid: String): String {
|
||||||
|
val name = contact.optString("name").trim().split(Regex("\\s+"))
|
||||||
|
val first = name.firstOrNull().orEmpty()
|
||||||
|
val last = name.drop(1).joinToString(" ")
|
||||||
|
return "BEGIN:VCARD\r\nVERSION:3.0\r\nUID:${escape(uid)}\r\nFN:${escape(contact.optString("name"))}\r\nN:${escape(last)};${escape(first)};;;\r\nEMAIL:${escape(contact.optString("email"))}\r\n${if (contact.optString("note").isNotBlank()) "NOTE:${escape(contact.optString("note"))}\r\n" else ""}END:VCARD\r\n"
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun propfindBody(homeSet: String) = """<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<d:propfind xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav" xmlns:a="urn:ietf:params:xml:ns:carddav">
|
||||||
|
<d:prop><d:current-user-principal/><d:displayname/><c:$homeSet/><a:$homeSet/></d:prop>
|
||||||
|
</d:propfind>""".trimIndent()
|
||||||
|
|
||||||
|
private fun collectionBody() = """<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<d:propfind xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav" xmlns:a="urn:ietf:params:xml:ns:carddav">
|
||||||
|
<d:prop><d:resourcetype/><d:displayname/><d:getetag/><c:calendar-data/><a:address-data/></d:prop>
|
||||||
|
</d:propfind>""".trimIndent()
|
||||||
|
|
||||||
|
private fun parseXml(bytes: ByteArray): org.w3c.dom.Document {
|
||||||
|
val factory = DocumentBuilderFactory.newInstance().apply {
|
||||||
|
isNamespaceAware = true
|
||||||
|
isXIncludeAware = false
|
||||||
|
isExpandEntityReferences = false
|
||||||
|
setFeature("http://apache.org/xml/features/disallow-doctype-decl", true)
|
||||||
|
setFeature("http://xml.org/sax/features/external-general-entities", false)
|
||||||
|
setFeature("http://xml.org/sax/features/external-parameter-entities", false)
|
||||||
|
}
|
||||||
|
return factory.newDocumentBuilder().parse(ByteArrayInputStream(bytes))
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun findHref(document: org.w3c.dom.Document, propertyName: String): String? {
|
||||||
|
val elements = document.getElementsByTagNameNS("*", propertyName)
|
||||||
|
for (index in 0 until elements.length) {
|
||||||
|
val href = (elements.item(index) as? Element)?.getElementsByTagNameNS("*", "href")?.item(0)?.textContent
|
||||||
|
if (!href.isNullOrBlank()) return href.trim()
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun textContent(element: Element, propertyName: String): String? {
|
||||||
|
val nodes = element.getElementsByTagNameNS("*", propertyName)
|
||||||
|
return if (nodes.length == 0) null else nodes.item(0)?.textContent?.trim()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun childText(element: Element, childName: String): String? {
|
||||||
|
val children = element.childNodes
|
||||||
|
for (index in 0 until children.length) {
|
||||||
|
val node = children.item(index)
|
||||||
|
if (node is Element && node.localName == childName) return node.textContent.trim()
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun resolveUrl(base: String, href: String): String = URL(URL(base), href).toString()
|
||||||
|
|
||||||
|
private fun basicAuth(account: JSONObject): String {
|
||||||
|
val raw = "${account.optString("username")}:${account.optString("password")}"
|
||||||
|
return "Basic " + Base64.encodeToString(raw.toByteArray(StandardCharsets.UTF_8), Base64.NO_WRAP)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun publicDav(account: JSONObject) = JSONObject()
|
||||||
|
.put("id", account.optString("id"))
|
||||||
|
.put("serverUrl", account.optString("serverUrl"))
|
||||||
|
.put("username", account.optString("username"))
|
||||||
|
.put("collections", account.optJSONArray("collections") ?: JSONArray())
|
||||||
|
|
||||||
|
private fun type(value: String) = when (value) {
|
||||||
|
"caldav", "carddav" -> value
|
||||||
|
else -> throw IllegalArgumentException("Choose a supported CalDAV or CardDAV account.")
|
||||||
}
|
}
|
||||||
|
|
||||||
fun connect(input: JSONObject): JSONObject {
|
private fun findCollection(collections: JSONArray, url: String): JSONObject? {
|
||||||
val type = type(input.optString("type"))
|
for (index in 0 until collections.length()) {
|
||||||
val serverUrl = input.optString("serverUrl").trim()
|
val collection = collections.getJSONObject(index)
|
||||||
val username = input.optString("username").trim()
|
if (url.isBlank() || collection.optString("url") == url) return collection
|
||||||
val password = input.optString("password")
|
}
|
||||||
val url = try { URL(serverUrl) } catch (_: Exception) {
|
return null
|
||||||
throw IllegalArgumentException("Enter a valid CalDAV or CardDAV server URL.")
|
}
|
||||||
}
|
|
||||||
require(url.protocol == "https" || (url.protocol == "http" && url.host in setOf("localhost", "127.0.0.1", "::1"))) {
|
private fun encode(value: String) = java.net.URLEncoder.encode(value, "UTF-8")
|
||||||
"DAV server URLs must use HTTPS."
|
private fun escape(value: String) = value.replace("\\", "\\\\").replace("\n", "\\n").replace(",", "\\,").replace(";", "\\;")
|
||||||
}
|
private fun unescape(value: String) = value.replace("\\n", "\n").replace("\\,", ",").replace("\\;", ";").replace("\\\\", "\\")
|
||||||
require(username.isNotBlank() && password.isNotBlank()) { "Enter the DAV username and password." }
|
private fun property(name: String, value: String) = if (value.isBlank()) "" else "$name:${escape(value)}\r\n"
|
||||||
val collections = discoverCollections(url.toString(), username, password, type)
|
private fun utcNow() = java.text.SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'", Locale.ROOT)
|
||||||
require(collections.length() > 0) {
|
.apply { timeZone = java.util.TimeZone.getTimeZone("UTC") }.format(java.util.Date())
|
||||||
"No ${if (type == "caldav") "calendars" else "address books"} were found on this server."
|
|
||||||
}
|
private fun unfold(data: String) = data.replace("\r\n ", "").replace("\n ", "").replace("\r\n\t", "").replace("\n\t", "")
|
||||||
val account = JSONObject()
|
|
||||||
.put("id", UUID.randomUUID().toString())
|
private fun parseProperties(block: String): Map<String, String> {
|
||||||
.put("type", type)
|
val result = LinkedHashMap<String, String>()
|
||||||
.put("serverUrl", url.toString())
|
for (line in block.lines()) {
|
||||||
.put("username", username)
|
val colon = line.indexOf(':')
|
||||||
.put("password", password)
|
if (colon <= 0) continue
|
||||||
.put("collections", collections)
|
val name = line.substring(0, colon).substringBefore(';').uppercase(Locale.ROOT)
|
||||||
val saved = AndroidAccountVault.putDavAccount(type, account)
|
result.putIfAbsent(name, line.substring(colon + 1).trim())
|
||||||
val publicConfig = publicDav(saved)
|
}
|
||||||
return JSONObject()
|
return result
|
||||||
.put("config", publicConfig)
|
}
|
||||||
.put("collections", collections)
|
|
||||||
.put("accounts", list())
|
private fun parseDate(raw: String): Pair<String, String>? {
|
||||||
}
|
if (raw.isBlank()) return null
|
||||||
|
val rawValue = raw.substringAfter(':', raw)
|
||||||
fun activate(typeInput: String, id: String): JSONObject {
|
return try {
|
||||||
val type = type(typeInput)
|
when {
|
||||||
val config = AndroidAccountVault.activeDav(type, id)
|
rawValue.length == 8 -> "${rawValue.substring(0, 4)}-${rawValue.substring(4, 6)}-${rawValue.substring(6, 8)}" to ""
|
||||||
?: throw IllegalStateException("That DAV account could not be found.")
|
rawValue.length >= 15 -> {
|
||||||
val store = AndroidAccountVault.read()
|
val digits = rawValue.replace("T", "").replace("Z", "").take(14)
|
||||||
store.put(if (type == "caldav") "activeCaldavId" else "activeCarddavId", config.optString("id"))
|
val date = "${digits.substring(0, 4)}-${digits.substring(4, 6)}-${digits.substring(6, 8)}"
|
||||||
AndroidAccountVault.write(store)
|
val time = "${digits.substring(8, 10)}:${digits.substring(10, 12)}"
|
||||||
return JSONObject().put("id", config.optString("id"))
|
date to time
|
||||||
}
|
}
|
||||||
|
else -> null
|
||||||
fun remove(typeInput: String, id: String): JSONObject =
|
}
|
||||||
AndroidAccountVault.removeDavAccount(type(typeInput), id)
|
} catch (_: Exception) { null }
|
||||||
|
}
|
||||||
fun sync(typeInput: String): JSONObject {
|
}
|
||||||
val type = type(typeInput)
|
|
||||||
val account = AndroidAccountVault.activeDav(type)
|
|
||||||
?: throw IllegalStateException("Connect a ${if (type == "caldav") "CalDAV" else "CardDAV"} server first.")
|
|
||||||
val collectionKey = if (type == "caldav") "calendar" else "addressbook"
|
|
||||||
val result = JSONArray()
|
|
||||||
val collections = account.optJSONArray("collections") ?: JSONArray()
|
|
||||||
for (index in 0 until collections.length()) {
|
|
||||||
val collection = collections.getJSONObject(index)
|
|
||||||
val objects = listObjects(account, collection, type)
|
|
||||||
for (obj in objects) {
|
|
||||||
val href = obj.optString("href")
|
|
||||||
val data = obj.optString("data")
|
|
||||||
if (data.isBlank()) continue
|
|
||||||
if (type == "caldav") parseCalendar(data, account, collection, obj).forEach(result::put)
|
|
||||||
else parseContacts(data, account, collection, obj).forEach(result::put)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return JSONObject().put("items", result).put("account", publicDav(account))
|
|
||||||
.put("collectionType", collectionKey)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun saveEvent(input: JSONObject): JSONObject? {
|
|
||||||
val remote = input.optJSONObject("_dav") ?: JSONObject()
|
|
||||||
val account = AndroidAccountVault.activeDav("caldav", remote.optString("accountId").ifBlank { null }) ?: return null
|
|
||||||
val collections = account.optJSONArray("collections") ?: JSONArray()
|
|
||||||
val collection = findCollection(collections, remote.optString("collectionUrl"))
|
|
||||||
?: throw IllegalStateException("No writable calendar was found.")
|
|
||||||
val uid = remote.optString("uid").ifBlank { UUID.randomUUID().toString() }
|
|
||||||
val filename = "$uid.ics"
|
|
||||||
val collectionUrl = collection.optString("url")
|
|
||||||
val target = remote.optString("objectUrl").ifBlank { collectionUrl.trimEnd('/') + "/" + filename }
|
|
||||||
val data = calendarData(input, uid)
|
|
||||||
val response = request(account, target, "PUT", data, mapOf("Content-Type" to "text/calendar; charset=utf-8"))
|
|
||||||
require(response.code in 200..299) { "The calendar server rejected the event (${response.code})." }
|
|
||||||
return JSONObject()
|
|
||||||
.put("accountId", account.optString("id"))
|
|
||||||
.put("collectionUrl", collectionUrl)
|
|
||||||
.put("objectUrl", target)
|
|
||||||
.put("etag", response.headers["etag"] ?: remote.optString("etag"))
|
|
||||||
.put("uid", uid)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun deleteEvent(remote: JSONObject) {
|
|
||||||
val account = AndroidAccountVault.activeDav("caldav", remote.optString("accountId"))
|
|
||||||
?: throw IllegalStateException("That calendar account could not be found.")
|
|
||||||
val url = remote.optString("objectUrl")
|
|
||||||
if (url.isBlank()) return
|
|
||||||
val response = request(account, url, "DELETE", null)
|
|
||||||
require(response.code in 200..299 || response.code == 404) { "The calendar server rejected the deletion (${response.code})." }
|
|
||||||
}
|
|
||||||
|
|
||||||
fun saveContact(input: JSONObject): JSONObject? {
|
|
||||||
val remote = input.optJSONObject("_dav") ?: JSONObject()
|
|
||||||
val account = AndroidAccountVault.activeDav("carddav", remote.optString("accountId").ifBlank { null }) ?: return null
|
|
||||||
val collections = account.optJSONArray("collections") ?: JSONArray()
|
|
||||||
val collection = findCollection(collections, remote.optString("collectionUrl"))
|
|
||||||
?: throw IllegalStateException("No writable address book was found.")
|
|
||||||
val uid = remote.optString("uid").ifBlank { UUID.randomUUID().toString() }
|
|
||||||
val filename = "$uid.vcf"
|
|
||||||
val collectionUrl = collection.optString("url")
|
|
||||||
val target = remote.optString("objectUrl").ifBlank { collectionUrl.trimEnd('/') + "/" + filename }
|
|
||||||
val response = request(account, target, "PUT", vcardData(input, uid), mapOf("Content-Type" to "text/vcard; charset=utf-8"))
|
|
||||||
require(response.code in 200..299) { "The address book server rejected the contact (${response.code})." }
|
|
||||||
return JSONObject()
|
|
||||||
.put("accountId", account.optString("id"))
|
|
||||||
.put("collectionUrl", collectionUrl)
|
|
||||||
.put("objectUrl", target)
|
|
||||||
.put("etag", response.headers["etag"] ?: remote.optString("etag"))
|
|
||||||
.put("uid", uid)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun deleteContact(remote: JSONObject) {
|
|
||||||
val account = AndroidAccountVault.activeDav("carddav", remote.optString("accountId"))
|
|
||||||
?: throw IllegalStateException("That address book account could not be found.")
|
|
||||||
val url = remote.optString("objectUrl")
|
|
||||||
if (url.isBlank()) return
|
|
||||||
val response = request(account, url, "DELETE", null)
|
|
||||||
require(response.code in 200..299 || response.code == 404) { "The address book server rejected the deletion (${response.code})." }
|
|
||||||
}
|
|
||||||
|
|
||||||
private data class HttpResult(val code: Int, val body: ByteArray, val headers: Map<String, String>)
|
|
||||||
|
|
||||||
private fun request(
|
|
||||||
account: JSONObject,
|
|
||||||
address: String,
|
|
||||||
method: String,
|
|
||||||
body: String?,
|
|
||||||
headers: Map<String, String> = emptyMap()
|
|
||||||
): HttpResult {
|
|
||||||
val target = URL(address)
|
|
||||||
val base = URL(account.optString("serverUrl"))
|
|
||||||
val targetPort = if (target.port >= 0) target.port else target.defaultPort
|
|
||||||
val basePort = if (base.port >= 0) base.port else base.defaultPort
|
|
||||||
require(target.protocol == base.protocol && target.host.equals(base.host, true) && targetPort == basePort) {
|
|
||||||
"The DAV server returned a collection URL on an unexpected host."
|
|
||||||
}
|
|
||||||
val requestBody = body?.toRequestBody(headers["Content-Type"]?.toMediaTypeOrNull())
|
|
||||||
val builder = Request.Builder()
|
|
||||||
.url(address)
|
|
||||||
.header("Authorization", basicAuth(account))
|
|
||||||
.header("User-Agent", "ep-mail-Android")
|
|
||||||
for ((key, value) in headers) builder.header(key, value)
|
|
||||||
builder.method(method, requestBody)
|
|
||||||
httpClient.newCall(builder.build()).execute().use { response ->
|
|
||||||
val bytes = response.body?.bytes() ?: ByteArray(0)
|
|
||||||
val responseHeaders = response.headers.toMultimap().mapValues { (_, values) -> values.firstOrNull().orEmpty() }
|
|
||||||
return HttpResult(response.code, bytes, responseHeaders)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun discoverCollections(serverUrl: String, username: String, password: String, type: String): JSONArray {
|
|
||||||
val base = JSONObject().put("serverUrl", serverUrl).put("username", username).put("password", password)
|
|
||||||
val setName = if (type == "caldav") "calendar-home-set" else "addressbook-home-set"
|
|
||||||
val rootResponse = request(base, serverUrl, "PROPFIND", propfindBody(setName), mapOf(
|
|
||||||
"Depth" to "0",
|
|
||||||
"Content-Type" to "application/xml; charset=utf-8"
|
|
||||||
))
|
|
||||||
require(rootResponse.code in 200..299 || rootResponse.code == 207) {
|
|
||||||
"Could not access the DAV server (${rootResponse.code})."
|
|
||||||
}
|
|
||||||
val rootDocument = parseXml(rootResponse.body)
|
|
||||||
var homeUrl = findHref(rootDocument, setName)?.let { resolveUrl(serverUrl, it) }
|
|
||||||
if (homeUrl == null) {
|
|
||||||
val principal = findHref(rootDocument, "current-user-principal")
|
|
||||||
if (principal != null) {
|
|
||||||
val principalUrl = resolveUrl(serverUrl, principal)
|
|
||||||
val principalResponse = request(base, principalUrl, "PROPFIND", propfindBody(setName), mapOf(
|
|
||||||
"Depth" to "0",
|
|
||||||
"Content-Type" to "application/xml; charset=utf-8"
|
|
||||||
))
|
|
||||||
if (principalResponse.code in 200..299 || principalResponse.code == 207) {
|
|
||||||
homeUrl = findHref(parseXml(principalResponse.body), setName)?.let { resolveUrl(principalUrl, it) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
val collectionUrl = homeUrl ?: serverUrl
|
|
||||||
val response = request(base, collectionUrl, "PROPFIND", collectionBody(), mapOf(
|
|
||||||
"Depth" to "1",
|
|
||||||
"Content-Type" to "application/xml; charset=utf-8"
|
|
||||||
))
|
|
||||||
require(response.code in 200..299 || response.code == 207) {
|
|
||||||
"Could not discover DAV collections (${response.code})."
|
|
||||||
}
|
|
||||||
val document = parseXml(response.body)
|
|
||||||
val requiredType = if (type == "caldav") "calendar" else "addressbook"
|
|
||||||
val result = JSONArray()
|
|
||||||
val responses = document.getElementsByTagNameNS("*", "response")
|
|
||||||
for (index in 0 until responses.length) {
|
|
||||||
val responseElement = responses.item(index) as? Element ?: continue
|
|
||||||
val href = childText(responseElement, "href") ?: continue
|
|
||||||
if (responseElement.getElementsByTagNameNS("*", requiredType).length == 0) continue
|
|
||||||
val resolved = resolveUrl(collectionUrl, href)
|
|
||||||
val displayName = textContent(responseElement, "displayname").orEmpty().ifBlank { resolved }
|
|
||||||
result.put(JSONObject().put("url", resolved).put("name", displayName))
|
|
||||||
}
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun listObjects(account: JSONObject, collection: JSONObject, type: String): List<JSONObject> {
|
|
||||||
val collectionUrl = collection.optString("url")
|
|
||||||
val response = request(account, collectionUrl, "PROPFIND", collectionBody(), mapOf(
|
|
||||||
"Depth" to "1",
|
|
||||||
"Content-Type" to "application/xml; charset=utf-8"
|
|
||||||
))
|
|
||||||
require(response.code in 200..299 || response.code == 207) {
|
|
||||||
"Could not read DAV collection ${collection.optString("name")} (${response.code})."
|
|
||||||
}
|
|
||||||
val document = parseXml(response.body)
|
|
||||||
val responses = document.getElementsByTagNameNS("*", "response")
|
|
||||||
val result = ArrayList<JSONObject>()
|
|
||||||
for (index in 0 until responses.length) {
|
|
||||||
val element = responses.item(index) as? Element ?: continue
|
|
||||||
val href = childText(element, "href") ?: continue
|
|
||||||
val objectUrl = resolveUrl(collectionUrl, href)
|
|
||||||
if (objectUrl.trimEnd('/') == collectionUrl.trimEnd('/')) continue
|
|
||||||
val data = if (type == "caldav") textContent(element, "calendar-data") else textContent(element, "address-data")
|
|
||||||
val content = if (!data.isNullOrBlank()) data else {
|
|
||||||
val fetched = request(account, objectUrl, "GET", null)
|
|
||||||
if (fetched.code !in 200..299) continue
|
|
||||||
String(fetched.body, StandardCharsets.UTF_8)
|
|
||||||
}
|
|
||||||
result.add(JSONObject()
|
|
||||||
.put("href", objectUrl)
|
|
||||||
.put("etag", textContent(element, "getetag").orEmpty())
|
|
||||||
.put("data", content))
|
|
||||||
}
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun parseCalendar(data: String, account: JSONObject, collection: JSONObject, resource: JSONObject): List<JSONObject> {
|
|
||||||
val unfolded = unfold(data)
|
|
||||||
return Regex("BEGIN:VEVENT(.*?)END:VEVENT", setOf(RegexOption.IGNORE_CASE, RegexOption.DOT_MATCHES_ALL))
|
|
||||||
.findAll(unfolded).mapNotNull { match ->
|
|
||||||
val block = match.groupValues[1]
|
|
||||||
val fields = parseProperties(block)
|
|
||||||
val uid = fields["UID"].orEmpty().ifBlank { UUID.randomUUID().toString() }
|
|
||||||
val (date, time) = parseDate(fields["DTSTART"].orEmpty()) ?: return@mapNotNull null
|
|
||||||
JSONObject()
|
|
||||||
.put("id", "dav:${account.optString("id")}:${encode(resource.optString("href"))}:${encode(uid)}")
|
|
||||||
.put("title", unescape(fields["SUMMARY"].orEmpty()).ifBlank { "(no title)" })
|
|
||||||
.put("date", date)
|
|
||||||
.put("time", time)
|
|
||||||
.put("with", Regex("(?im)^ATTENDEE[^:]*:(?:mailto:)?([^\\r\\n]+)").findAll(block)
|
|
||||||
.map { it.groupValues[1].trim() }.joinToString(", "))
|
|
||||||
.put("place", unescape(fields["LOCATION"].orEmpty()))
|
|
||||||
.put("notes", unescape(fields["DESCRIPTION"].orEmpty()))
|
|
||||||
.put("_dav", JSONObject()
|
|
||||||
.put("accountId", account.optString("id"))
|
|
||||||
.put("collectionUrl", collection.optString("url"))
|
|
||||||
.put("objectUrl", resource.optString("href"))
|
|
||||||
.put("etag", resource.optString("etag"))
|
|
||||||
.put("uid", uid))
|
|
||||||
}.toList()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun parseContacts(data: String, account: JSONObject, collection: JSONObject, resource: JSONObject): List<JSONObject> {
|
|
||||||
val cards = Regex("BEGIN:VCARD(.*?)END:VCARD", setOf(RegexOption.IGNORE_CASE, RegexOption.DOT_MATCHES_ALL))
|
|
||||||
return cards.findAll(unfold(data)).mapNotNull { match ->
|
|
||||||
val block = match.groupValues[1]
|
|
||||||
val fields = parseProperties(block)
|
|
||||||
val name = unescape(fields["FN"].orEmpty()).trim()
|
|
||||||
if (name.isBlank()) return@mapNotNull null
|
|
||||||
val uid = fields["UID"].orEmpty()
|
|
||||||
JSONObject()
|
|
||||||
.put("id", "dav:${account.optString("id")}:${encode(resource.optString("href"))}:${encode(uid)}")
|
|
||||||
.put("name", name)
|
|
||||||
.put("email", unescape(fields["EMAIL"].orEmpty()))
|
|
||||||
.put("note", unescape(fields["NOTE"].orEmpty()))
|
|
||||||
.put("initials", name.split(Regex("\\s+")).mapNotNull { it.firstOrNull()?.toString() }
|
|
||||||
.joinToString("").take(2).uppercase(Locale.getDefault()))
|
|
||||||
.put("color", "#dce9dd")
|
|
||||||
.put("_dav", JSONObject()
|
|
||||||
.put("accountId", account.optString("id"))
|
|
||||||
.put("collectionUrl", collection.optString("url"))
|
|
||||||
.put("objectUrl", resource.optString("href"))
|
|
||||||
.put("etag", resource.optString("etag"))
|
|
||||||
.put("uid", uid))
|
|
||||||
}.toList()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun calendarData(event: JSONObject, uid: String): String {
|
|
||||||
val date = event.optString("date").replace("-", "")
|
|
||||||
val time = event.optString("time")
|
|
||||||
val start = if (time.isBlank()) "DTSTART;VALUE=DATE:$date" else "DTSTART;TZID=UTC:${date}T${time.replace(":", "")}00"
|
|
||||||
val end = if (time.isBlank()) "" else {
|
|
||||||
val parts = time.split(":")
|
|
||||||
val mins = (parts.getOrNull(0)?.toIntOrNull() ?: 0) * 60 + (parts.getOrNull(1)?.toIntOrNull() ?: 0) + 60
|
|
||||||
val endTime = "%04d%02d00".format(Locale.ROOT, (mins / 60) % 24, mins % 60)
|
|
||||||
"DTEND;TZID=UTC:${date}T$endTime\r\n"
|
|
||||||
}
|
|
||||||
return "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Eternity Project//ep-mail CalDAV\r\nBEGIN:VEVENT\r\nUID:${escape(uid)}\r\nDTSTAMP:${utcNow()}\r\n$start\r\n$end${property("SUMMARY", event.optString("title"))}${property("LOCATION", event.optString("place"))}${property("DESCRIPTION", event.optString("notes"))}END:VEVENT\r\nEND:VCALENDAR\r\n"
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun vcardData(contact: JSONObject, uid: String): String {
|
|
||||||
val name = contact.optString("name").trim().split(Regex("\\s+"))
|
|
||||||
val first = name.firstOrNull().orEmpty()
|
|
||||||
val last = name.drop(1).joinToString(" ")
|
|
||||||
return "BEGIN:VCARD\r\nVERSION:3.0\r\nUID:${escape(uid)}\r\nFN:${escape(contact.optString("name"))}\r\nN:${escape(last)};${escape(first)};;;\r\nEMAIL:${escape(contact.optString("email"))}\r\n${if (contact.optString("note").isNotBlank()) "NOTE:${escape(contact.optString("note"))}\r\n" else ""}END:VCARD\r\n"
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun propfindBody(homeSet: String) = """<?xml version="1.0" encoding="utf-8"?>
|
|
||||||
<d:propfind xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav" xmlns:a="urn:ietf:params:xml:ns:carddav">
|
|
||||||
<d:prop><d:current-user-principal/><d:displayname/><c:$homeSet/><a:$homeSet/></d:prop>
|
|
||||||
</d:propfind>""".trimIndent()
|
|
||||||
|
|
||||||
private fun collectionBody() = """<?xml version="1.0" encoding="utf-8"?>
|
|
||||||
<d:propfind xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav" xmlns:a="urn:ietf:params:xml:ns:carddav">
|
|
||||||
<d:prop><d:resourcetype/><d:displayname/><d:getetag/><c:calendar-data/><a:address-data/></d:prop>
|
|
||||||
</d:propfind>""".trimIndent()
|
|
||||||
|
|
||||||
private fun parseXml(bytes: ByteArray): org.w3c.dom.Document {
|
|
||||||
val factory = DocumentBuilderFactory.newInstance().apply {
|
|
||||||
isNamespaceAware = true
|
|
||||||
isXIncludeAware = false
|
|
||||||
isExpandEntityReferences = false
|
|
||||||
setFeature("http://apache.org/xml/features/disallow-doctype-decl", true)
|
|
||||||
setFeature("http://xml.org/sax/features/external-general-entities", false)
|
|
||||||
setFeature("http://xml.org/sax/features/external-parameter-entities", false)
|
|
||||||
}
|
|
||||||
return factory.newDocumentBuilder().parse(ByteArrayInputStream(bytes))
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun findHref(document: org.w3c.dom.Document, propertyName: String): String? {
|
|
||||||
val elements = document.getElementsByTagNameNS("*", propertyName)
|
|
||||||
for (index in 0 until elements.length) {
|
|
||||||
val href = (elements.item(index) as? Element)?.getElementsByTagNameNS("*", "href")?.item(0)?.textContent
|
|
||||||
if (!href.isNullOrBlank()) return href.trim()
|
|
||||||
}
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun textContent(element: Element, propertyName: String): String? {
|
|
||||||
val nodes = element.getElementsByTagNameNS("*", propertyName)
|
|
||||||
return if (nodes.length == 0) null else nodes.item(0)?.textContent?.trim()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun childText(element: Element, childName: String): String? {
|
|
||||||
val children = element.childNodes
|
|
||||||
for (index in 0 until children.length) {
|
|
||||||
val node = children.item(index)
|
|
||||||
if (node is Element && node.localName == childName) return node.textContent.trim()
|
|
||||||
}
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun resolveUrl(base: String, href: String): String = URL(URL(base), href).toString()
|
|
||||||
|
|
||||||
private fun basicAuth(account: JSONObject): String {
|
|
||||||
val raw = "${account.optString("username")}:${account.optString("password")}"
|
|
||||||
return "Basic " + Base64.encodeToString(raw.toByteArray(StandardCharsets.UTF_8), Base64.NO_WRAP)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun publicDav(account: JSONObject) = JSONObject()
|
|
||||||
.put("id", account.optString("id"))
|
|
||||||
.put("serverUrl", account.optString("serverUrl"))
|
|
||||||
.put("username", account.optString("username"))
|
|
||||||
.put("collections", account.optJSONArray("collections") ?: JSONArray())
|
|
||||||
|
|
||||||
private fun type(value: String) = if (value == "carddav") "carddav" else "caldav"
|
|
||||||
|
|
||||||
private fun findCollection(collections: JSONArray, url: String): JSONObject? {
|
|
||||||
for (index in 0 until collections.length()) {
|
|
||||||
val collection = collections.getJSONObject(index)
|
|
||||||
if (url.isBlank() || collection.optString("url") == url) return collection
|
|
||||||
}
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun encode(value: String) = java.net.URLEncoder.encode(value, "UTF-8")
|
|
||||||
private fun escape(value: String) = value.replace("\\", "\\\\").replace("\n", "\\n").replace(",", "\\,").replace(";", "\\;")
|
|
||||||
private fun unescape(value: String) = value.replace("\\n", "\n").replace("\\,", ",").replace("\\;", ";").replace("\\\\", "\\")
|
|
||||||
private fun property(name: String, value: String) = if (value.isBlank()) "" else "$name:${escape(value)}\r\n"
|
|
||||||
private fun utcNow() = java.text.SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'", Locale.ROOT)
|
|
||||||
.apply { timeZone = java.util.TimeZone.getTimeZone("UTC") }.format(java.util.Date())
|
|
||||||
|
|
||||||
private fun unfold(data: String) = data.replace("\r\n ", "").replace("\n ", "").replace("\r\n\t", "").replace("\n\t", "")
|
|
||||||
|
|
||||||
private fun parseProperties(block: String): Map<String, String> {
|
|
||||||
val result = LinkedHashMap<String, String>()
|
|
||||||
for (line in block.lines()) {
|
|
||||||
val colon = line.indexOf(':')
|
|
||||||
if (colon <= 0) continue
|
|
||||||
val name = line.substring(0, colon).substringBefore(';').uppercase(Locale.ROOT)
|
|
||||||
result.putIfAbsent(name, line.substring(colon + 1).trim())
|
|
||||||
}
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun parseDate(raw: String): Pair<String, String>? {
|
|
||||||
if (raw.isBlank()) return null
|
|
||||||
val rawValue = raw.substringAfter(':', raw)
|
|
||||||
return try {
|
|
||||||
when {
|
|
||||||
rawValue.length == 8 -> "${rawValue.substring(0, 4)}-${rawValue.substring(4, 6)}-${rawValue.substring(6, 8)}" to ""
|
|
||||||
rawValue.length >= 15 -> {
|
|
||||||
val digits = rawValue.replace("T", "").replace("Z", "").take(14)
|
|
||||||
val date = "${digits.substring(0, 4)}-${digits.substring(4, 6)}-${digits.substring(6, 8)}"
|
|
||||||
val time = "${digits.substring(8, 10)}:${digits.substring(10, 12)}"
|
|
||||||
date to time
|
|
||||||
}
|
|
||||||
else -> null
|
|
||||||
}
|
|
||||||
} catch (_: Exception) { null }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -0,0 +1,11 @@
|
|||||||
|
package studio.daybreak.mail
|
||||||
|
|
||||||
|
internal object AttachmentNamePolicy {
|
||||||
|
fun sanitize(value: String): String {
|
||||||
|
val name = value
|
||||||
|
.replace(Regex("[\\\\/:*?\"<>|\\u0000-\\u001f]"), "_")
|
||||||
|
.trim()
|
||||||
|
.take(180)
|
||||||
|
return if (name.isBlank() || name == "." || name == "..") "attachment" else name
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
package studio.daybreak.mail
|
||||||
|
|
||||||
|
import java.net.URL
|
||||||
|
|
||||||
|
/** Enforces the transport and origin policy for user-configured DAV endpoints. */
|
||||||
|
internal object DavUrlPolicy {
|
||||||
|
fun parseServerUrl(raw: String): URL {
|
||||||
|
val url = try {
|
||||||
|
URL(raw)
|
||||||
|
} catch (_: Exception) {
|
||||||
|
throw IllegalArgumentException("Enter a valid CalDAV or CardDAV server URL.")
|
||||||
|
}
|
||||||
|
require(url.protocol.equals("https", ignoreCase = true) && url.host.isNotBlank()) {
|
||||||
|
"DAV server URLs must use HTTPS."
|
||||||
|
}
|
||||||
|
require(url.userInfo == null && url.ref == null) {
|
||||||
|
"DAV server URLs cannot contain credentials or fragments."
|
||||||
|
}
|
||||||
|
return url
|
||||||
|
}
|
||||||
|
|
||||||
|
fun requireSameOrigin(baseAddress: String, targetAddress: String) {
|
||||||
|
val base = parseServerUrl(baseAddress)
|
||||||
|
val target = parseServerUrl(targetAddress)
|
||||||
|
val basePort = if (base.port >= 0) base.port else base.defaultPort
|
||||||
|
val targetPort = if (target.port >= 0) target.port else target.defaultPort
|
||||||
|
require(target.host.equals(base.host, ignoreCase = true) && targetPort == basePort) {
|
||||||
|
"The DAV server returned a collection URL on an unexpected host."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,55 +1,55 @@
|
|||||||
package studio.daybreak.mail
|
package studio.daybreak.mail
|
||||||
|
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import androidx.work.Constraints
|
import androidx.work.Constraints
|
||||||
import androidx.work.ExistingPeriodicWorkPolicy
|
import androidx.work.ExistingPeriodicWorkPolicy
|
||||||
import androidx.work.NetworkType
|
import androidx.work.NetworkType
|
||||||
import androidx.work.PeriodicWorkRequestBuilder
|
import androidx.work.PeriodicWorkRequestBuilder
|
||||||
import androidx.work.WorkManager
|
import androidx.work.WorkManager
|
||||||
import androidx.work.Worker
|
import androidx.work.Worker
|
||||||
import androidx.work.WorkerParameters
|
import androidx.work.WorkerParameters
|
||||||
import java.util.concurrent.TimeUnit
|
import java.util.concurrent.TimeUnit
|
||||||
|
|
||||||
class MailFallbackWorker(context: Context, parameters: WorkerParameters) : Worker(context, parameters) {
|
class MailFallbackWorker(context: Context, parameters: WorkerParameters) : Worker(context, parameters) {
|
||||||
override fun doWork(): Result {
|
override fun doWork(): Result {
|
||||||
return try {
|
return try {
|
||||||
AndroidAccountVault.initialize(applicationContext)
|
AndroidAccountVault.initialize(applicationContext)
|
||||||
MailIdleService.checkSnoozeReminders(applicationContext)
|
MailIdleService.checkSnoozeReminders(applicationContext)
|
||||||
val accounts = AndroidAccountVault.accounts()
|
val accounts = AndroidAccountVault.accounts()
|
||||||
for (index in 0 until accounts.length()) {
|
for (index in 0 until accounts.length()) {
|
||||||
val account = accounts.getJSONObject(index)
|
val account = accounts.getJSONObject(index)
|
||||||
val newMessages = AndroidMailService.checkForNewMail(account)
|
val newMessages = AndroidMailService.checkForNewMail(account)
|
||||||
if (newMessages > 0) {
|
if (newMessages > 0) {
|
||||||
MailIdleService.notifyNewMail(applicationContext, account, newMessages)
|
MailIdleService.notifyNewMail(applicationContext, account, newMessages)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Result.success()
|
Result.success()
|
||||||
} catch (error: Exception) {
|
} catch (error: Exception) {
|
||||||
android.util.Log.w(TAG, "Periodic mail fallback sync failed", error)
|
android.util.Log.w(TAG, "Periodic mail fallback sync failed (${error.javaClass.simpleName})")
|
||||||
Result.retry()
|
Result.retry()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
private const val TAG = "EpMailFallback"
|
private const val TAG = "EpMailFallback"
|
||||||
private const val UNIQUE_WORK_NAME = "ep-mail-periodic-sync"
|
private const val UNIQUE_WORK_NAME = "ep-mail-periodic-sync"
|
||||||
|
|
||||||
fun schedule(context: Context) {
|
fun schedule(context: Context) {
|
||||||
val constraints = Constraints.Builder()
|
val constraints = Constraints.Builder()
|
||||||
.setRequiredNetworkType(NetworkType.CONNECTED)
|
.setRequiredNetworkType(NetworkType.CONNECTED)
|
||||||
.build()
|
.build()
|
||||||
val request = PeriodicWorkRequestBuilder<MailFallbackWorker>(15, TimeUnit.MINUTES)
|
val request = PeriodicWorkRequestBuilder<MailFallbackWorker>(15, TimeUnit.MINUTES)
|
||||||
.setConstraints(constraints)
|
.setConstraints(constraints)
|
||||||
.build()
|
.build()
|
||||||
WorkManager.getInstance(context.applicationContext).enqueueUniquePeriodicWork(
|
WorkManager.getInstance(context.applicationContext).enqueueUniquePeriodicWork(
|
||||||
UNIQUE_WORK_NAME,
|
UNIQUE_WORK_NAME,
|
||||||
ExistingPeriodicWorkPolicy.KEEP,
|
ExistingPeriodicWorkPolicy.KEEP,
|
||||||
request
|
request
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun cancel(context: Context) {
|
fun cancel(context: Context) {
|
||||||
WorkManager.getInstance(context.applicationContext).cancelUniqueWork(UNIQUE_WORK_NAME)
|
WorkManager.getInstance(context.applicationContext).cancelUniqueWork(UNIQUE_WORK_NAME)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,295 +1,297 @@
|
|||||||
package studio.daybreak.mail
|
package studio.daybreak.mail
|
||||||
|
|
||||||
import android.app.Notification
|
import android.app.Notification
|
||||||
import android.app.NotificationChannel
|
import android.app.NotificationChannel
|
||||||
import android.app.NotificationManager
|
import android.app.NotificationManager
|
||||||
import android.app.PendingIntent
|
import android.app.PendingIntent
|
||||||
import android.app.Service
|
import android.app.Service
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
import android.os.IBinder
|
import android.os.IBinder
|
||||||
import androidx.core.app.NotificationCompat
|
import androidx.core.app.NotificationCompat
|
||||||
import androidx.core.app.NotificationManagerCompat
|
import androidx.core.app.NotificationManagerCompat
|
||||||
import java.util.concurrent.ConcurrentHashMap
|
import java.util.concurrent.ConcurrentHashMap
|
||||||
import java.util.concurrent.atomic.AtomicBoolean
|
import java.util.concurrent.atomic.AtomicBoolean
|
||||||
import org.json.JSONObject
|
import org.json.JSONObject
|
||||||
import javax.mail.Folder
|
import javax.mail.Folder
|
||||||
import javax.mail.Store
|
import javax.mail.Store
|
||||||
|
|
||||||
class MailIdleService : Service() {
|
class MailIdleService : Service() {
|
||||||
private data class Watcher(
|
private data class Watcher(
|
||||||
val account: JSONObject,
|
val account: JSONObject,
|
||||||
val fingerprint: String,
|
val fingerprint: String,
|
||||||
val stopped: AtomicBoolean = AtomicBoolean(false),
|
val stopped: AtomicBoolean = AtomicBoolean(false),
|
||||||
@Volatile var store: Store? = null,
|
@Volatile var store: Store? = null,
|
||||||
@Volatile var folder: Folder? = null,
|
@Volatile var folder: Folder? = null,
|
||||||
@Volatile var thread: Thread? = null
|
@Volatile var thread: Thread? = null
|
||||||
) {
|
) {
|
||||||
fun stop() {
|
fun stop() {
|
||||||
stopped.set(true)
|
stopped.set(true)
|
||||||
try { folder?.close(false) } catch (_: Exception) {}
|
try { folder?.close(false) } catch (_: Exception) {}
|
||||||
try { store?.close() } catch (_: Exception) {}
|
try { store?.close() } catch (_: Exception) {}
|
||||||
thread?.interrupt()
|
thread?.interrupt()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private val watchers = ConcurrentHashMap<String, Watcher>()
|
private val watchers = ConcurrentHashMap<String, Watcher>()
|
||||||
|
|
||||||
override fun onCreate() {
|
override fun onCreate() {
|
||||||
super.onCreate()
|
super.onCreate()
|
||||||
AndroidAccountVault.initialize(applicationContext)
|
AndroidAccountVault.initialize(applicationContext)
|
||||||
createNotificationChannels()
|
createNotificationChannels()
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||||
startForeground(FOREGROUND_NOTIFICATION_ID, foregroundNotification())
|
startForeground(FOREGROUND_NOTIFICATION_ID, foregroundNotification())
|
||||||
Thread {
|
Thread {
|
||||||
try {
|
try {
|
||||||
reconcile()
|
reconcile()
|
||||||
if (watchers.isEmpty()) stopSelf(startId)
|
if (watchers.isEmpty()) stopSelf(startId)
|
||||||
} catch (error: Exception) {
|
} catch (error: Exception) {
|
||||||
android.util.Log.e(TAG, "Could not start mailbox watchers", error)
|
android.util.Log.e(TAG, "Could not start mailbox watchers (${error.javaClass.simpleName})")
|
||||||
}
|
}
|
||||||
}.start()
|
}.start()
|
||||||
return START_STICKY
|
return START_STICKY
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onBind(intent: Intent?): IBinder? = null
|
override fun onBind(intent: Intent?): IBinder? = null
|
||||||
|
|
||||||
override fun onDestroy() {
|
override fun onDestroy() {
|
||||||
watchers.values.forEach(Watcher::stop)
|
watchers.values.forEach(Watcher::stop)
|
||||||
watchers.clear()
|
watchers.clear()
|
||||||
super.onDestroy()
|
super.onDestroy()
|
||||||
}
|
}
|
||||||
|
|
||||||
@Synchronized
|
@Synchronized
|
||||||
private fun reconcile() {
|
private fun reconcile() {
|
||||||
val accounts = AndroidAccountVault.accounts()
|
val accounts = AndroidAccountVault.accounts()
|
||||||
val desired = LinkedHashMap<String, JSONObject>()
|
val desired = LinkedHashMap<String, JSONObject>()
|
||||||
for (index in 0 until accounts.length().coerceAtMost(MAX_WATCHERS)) {
|
for (index in 0 until accounts.length().coerceAtMost(MAX_WATCHERS)) {
|
||||||
val account = accounts.getJSONObject(index)
|
val account = accounts.getJSONObject(index)
|
||||||
desired[account.optString("id")] = account
|
desired[account.optString("id")] = account
|
||||||
}
|
}
|
||||||
|
|
||||||
for ((id, watcher) in watchers) {
|
for ((id, watcher) in watchers) {
|
||||||
val account = desired[id]
|
val account = desired[id]
|
||||||
if (account == null || AndroidMailService.accountFingerprint(account) != watcher.fingerprint) {
|
if (account == null || AndroidMailService.accountFingerprint(account) != watcher.fingerprint) {
|
||||||
watcher.stop()
|
watcher.stop()
|
||||||
watchers.remove(id, watcher)
|
watchers.remove(id, watcher)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for ((id, account) in desired) {
|
for ((id, account) in desired) {
|
||||||
if (!watchers.containsKey(id)) startWatcher(id, account)
|
if (!watchers.containsKey(id)) startWatcher(id, account)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun startWatcher(id: String, account: JSONObject) {
|
private fun startWatcher(id: String, account: JSONObject) {
|
||||||
val watcher = Watcher(account, AndroidMailService.accountFingerprint(account))
|
val watcher = Watcher(account, AndroidMailService.accountFingerprint(account))
|
||||||
watchers[id] = watcher
|
watchers[id] = watcher
|
||||||
val thread = Thread({
|
val thread = Thread({
|
||||||
var failures = 0
|
var failures = 0
|
||||||
while (!watcher.stopped.get()) {
|
while (!watcher.stopped.get()) {
|
||||||
try {
|
try {
|
||||||
AndroidMailService.watchInbox(
|
AndroidMailService.watchInbox(
|
||||||
account = account,
|
account = account,
|
||||||
onNewMail = { count -> onNewMail(account, count) },
|
onNewMail = { count -> onNewMail(account, count) },
|
||||||
shouldStop = { watcher.stopped.get() },
|
shouldStop = { watcher.stopped.get() },
|
||||||
onConnection = { store, folder ->
|
onConnection = { store, folder ->
|
||||||
watcher.store = store
|
watcher.store = store
|
||||||
watcher.folder = folder
|
watcher.folder = folder
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
failures = 0
|
failures = 0
|
||||||
} catch (error: Exception) {
|
} catch (error: Exception) {
|
||||||
if (!watcher.stopped.get()) android.util.Log.w(TAG, "IMAP watcher disconnected for ${account.optString("email")}", error)
|
if (!watcher.stopped.get()) {
|
||||||
failures += 1
|
android.util.Log.w(TAG, "IMAP watcher disconnected (${error.javaClass.simpleName})")
|
||||||
} finally {
|
|
||||||
watcher.folder = null
|
|
||||||
watcher.store = null
|
|
||||||
}
|
|
||||||
if (!watcher.stopped.get()) {
|
|
||||||
val delayMs = (15_000L * (1L shl failures.coerceAtMost(5))).coerceAtMost(5 * 60_000L)
|
|
||||||
try {
|
|
||||||
Thread.sleep(delayMs)
|
|
||||||
} catch (_: InterruptedException) {
|
|
||||||
if (watcher.stopped.get()) break
|
|
||||||
}
|
}
|
||||||
}
|
failures += 1
|
||||||
}
|
} finally {
|
||||||
}, "ep-mail-idle-$id")
|
watcher.folder = null
|
||||||
thread.isDaemon = true
|
watcher.store = null
|
||||||
watcher.thread = thread
|
}
|
||||||
thread.start()
|
if (!watcher.stopped.get()) {
|
||||||
}
|
val delayMs = (15_000L * (1L shl failures.coerceAtMost(5))).coerceAtMost(5 * 60_000L)
|
||||||
|
try {
|
||||||
private fun onNewMail(account: JSONObject, count: Int) {
|
Thread.sleep(delayMs)
|
||||||
notifyNewMail(this, account, count)
|
} catch (_: InterruptedException) {
|
||||||
}
|
if (watcher.stopped.get()) break
|
||||||
|
}
|
||||||
private fun foregroundNotification(): Notification = NotificationCompat.Builder(this, SERVICE_CHANNEL_ID)
|
}
|
||||||
.setSmallIcon(android.R.drawable.ic_dialog_email)
|
}
|
||||||
.setContentTitle(getString(R.string.app_name))
|
}, "ep-mail-idle-$id")
|
||||||
.setContentText("Checking mail in the background")
|
thread.isDaemon = true
|
||||||
.setContentIntent(appPendingIntent())
|
watcher.thread = thread
|
||||||
.setOngoing(true)
|
thread.start()
|
||||||
.setPriority(NotificationCompat.PRIORITY_LOW)
|
}
|
||||||
.build()
|
|
||||||
|
private fun onNewMail(account: JSONObject, count: Int) {
|
||||||
private fun appPendingIntent(): PendingIntent {
|
notifyNewMail(this, account, count)
|
||||||
val intent = packageManager.getLaunchIntentForPackage(packageName)
|
}
|
||||||
?: Intent(this, MainActivity::class.java)
|
|
||||||
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP)
|
private fun foregroundNotification(): Notification = NotificationCompat.Builder(this, SERVICE_CHANNEL_ID)
|
||||||
return PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
|
.setSmallIcon(android.R.drawable.ic_dialog_email)
|
||||||
}
|
.setContentTitle(getString(R.string.app_name))
|
||||||
|
.setContentText("Checking mail in the background")
|
||||||
private fun createNotificationChannels() {
|
.setContentIntent(appPendingIntent())
|
||||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
|
.setOngoing(true)
|
||||||
val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
|
.setPriority(NotificationCompat.PRIORITY_LOW)
|
||||||
manager.createNotificationChannel(NotificationChannel(
|
.build()
|
||||||
SERVICE_CHANNEL_ID,
|
|
||||||
"Background mail sync",
|
private fun appPendingIntent(): PendingIntent {
|
||||||
NotificationManager.IMPORTANCE_LOW
|
val intent = packageManager.getLaunchIntentForPackage(packageName)
|
||||||
).apply { description = "Keeps mail synchronized in the background." })
|
?: Intent(this, MainActivity::class.java)
|
||||||
manager.createNotificationChannel(NotificationChannel(
|
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP)
|
||||||
MAIL_CHANNEL_ID,
|
return PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
|
||||||
"New mail",
|
}
|
||||||
NotificationManager.IMPORTANCE_DEFAULT
|
|
||||||
).apply { description = "Notifies you when new mail arrives." })
|
private fun createNotificationChannels() {
|
||||||
}
|
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
|
||||||
|
val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
|
||||||
companion object {
|
manager.createNotificationChannel(NotificationChannel(
|
||||||
const val ACTION_MAIL_SYNC = "studio.daybreak.mail.MAIL_SYNC_UPDATE"
|
SERVICE_CHANNEL_ID,
|
||||||
const val EXTRA_SYNC_UPDATE = "syncUpdate"
|
"Background mail sync",
|
||||||
private const val TAG = "EpMailIdle"
|
NotificationManager.IMPORTANCE_LOW
|
||||||
private const val MAX_WATCHERS = 2
|
).apply { description = "Keeps mail synchronized in the background." })
|
||||||
private const val FOREGROUND_NOTIFICATION_ID = 3410
|
manager.createNotificationChannel(NotificationChannel(
|
||||||
private const val SERVICE_CHANNEL_ID = "mail-sync-service"
|
MAIL_CHANNEL_ID,
|
||||||
private const val MAIL_CHANNEL_ID = "mail-new-message"
|
"New mail",
|
||||||
|
NotificationManager.IMPORTANCE_DEFAULT
|
||||||
fun start(context: Context) {
|
).apply { description = "Notifies you when new mail arrives." })
|
||||||
AndroidAccountVault.initialize(context)
|
}
|
||||||
if (AndroidAccountVault.accounts().length() == 0) return
|
|
||||||
MailFallbackWorker.schedule(context)
|
companion object {
|
||||||
val intent = Intent(context, MailIdleService::class.java)
|
const val ACTION_MAIL_SYNC = "studio.daybreak.mail.MAIL_SYNC_UPDATE"
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) context.startForegroundService(intent)
|
const val EXTRA_SYNC_UPDATE = "syncUpdate"
|
||||||
else context.startService(intent)
|
private const val TAG = "EpMailIdle"
|
||||||
}
|
private const val MAX_WATCHERS = 2
|
||||||
|
private const val FOREGROUND_NOTIFICATION_ID = 3410
|
||||||
fun stop(context: Context) {
|
private const val SERVICE_CHANNEL_ID = "mail-sync-service"
|
||||||
context.stopService(Intent(context, MailIdleService::class.java))
|
private const val MAIL_CHANNEL_ID = "mail-new-message"
|
||||||
MailFallbackWorker.cancel(context)
|
|
||||||
}
|
fun start(context: Context) {
|
||||||
|
AndroidAccountVault.initialize(context)
|
||||||
fun checkSnoozeReminders(context: Context) {
|
if (AndroidAccountVault.accounts().length() == 0) return
|
||||||
AndroidAccountVault.initialize(context)
|
MailFallbackWorker.schedule(context)
|
||||||
val accounts = AndroidAccountVault.accounts()
|
val intent = Intent(context, MailIdleService::class.java)
|
||||||
for (index in 0 until accounts.length()) {
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) context.startForegroundService(intent)
|
||||||
val account = accounts.getJSONObject(index)
|
else context.startService(intent)
|
||||||
val reminders = AndroidAccountVault.takeDueSnoozes(
|
}
|
||||||
account.optString("id"),
|
|
||||||
System.currentTimeMillis()
|
fun stop(context: Context) {
|
||||||
)
|
context.stopService(Intent(context, MailIdleService::class.java))
|
||||||
for (reminderIndex in 0 until reminders.length()) {
|
MailFallbackWorker.cancel(context)
|
||||||
notifySnoozeReminder(context, account, reminders.getJSONObject(reminderIndex))
|
}
|
||||||
}
|
|
||||||
}
|
fun checkSnoozeReminders(context: Context) {
|
||||||
}
|
AndroidAccountVault.initialize(context)
|
||||||
|
val accounts = AndroidAccountVault.accounts()
|
||||||
fun notifyNewMail(context: Context, account: JSONObject, count: Int) {
|
for (index in 0 until accounts.length()) {
|
||||||
if (count <= 0) return
|
val account = accounts.getJSONObject(index)
|
||||||
val appContext = context.applicationContext
|
val reminders = AndroidAccountVault.takeDueSnoozes(
|
||||||
val email = account.optString("email")
|
account.optString("id"),
|
||||||
if (account.optBoolean("notificationsEnabled", true)) {
|
System.currentTimeMillis()
|
||||||
val notificationManager = appContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
|
)
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O &&
|
for (reminderIndex in 0 until reminders.length()) {
|
||||||
notificationManager.getNotificationChannel(MAIL_CHANNEL_ID) == null) {
|
notifySnoozeReminder(context, account, reminders.getJSONObject(reminderIndex))
|
||||||
notificationManager.createNotificationChannel(NotificationChannel(
|
}
|
||||||
MAIL_CHANNEL_ID,
|
}
|
||||||
"New mail",
|
}
|
||||||
NotificationManager.IMPORTANCE_DEFAULT
|
|
||||||
).apply { description = "Notifies you when new mail arrives." })
|
fun notifyNewMail(context: Context, account: JSONObject, count: Int) {
|
||||||
}
|
if (count <= 0) return
|
||||||
val launchIntent = appContext.packageManager.getLaunchIntentForPackage(appContext.packageName)
|
val appContext = context.applicationContext
|
||||||
?: Intent(appContext, MainActivity::class.java)
|
val email = account.optString("email")
|
||||||
launchIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP)
|
if (account.optBoolean("notificationsEnabled", true)) {
|
||||||
val pendingIntent = PendingIntent.getActivity(
|
val notificationManager = appContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
|
||||||
appContext, 0, launchIntent,
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O &&
|
||||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
|
notificationManager.getNotificationChannel(MAIL_CHANNEL_ID) == null) {
|
||||||
)
|
notificationManager.createNotificationChannel(NotificationChannel(
|
||||||
val title = if (count == 1) "New mail" else "$count new messages"
|
MAIL_CHANNEL_ID,
|
||||||
val notification = NotificationCompat.Builder(appContext, MAIL_CHANNEL_ID)
|
"New mail",
|
||||||
.setSmallIcon(android.R.drawable.ic_dialog_email)
|
NotificationManager.IMPORTANCE_DEFAULT
|
||||||
.setContentTitle(title)
|
).apply { description = "Notifies you when new mail arrives." })
|
||||||
.setContentText(email)
|
}
|
||||||
.setAutoCancel(true)
|
val launchIntent = appContext.packageManager.getLaunchIntentForPackage(appContext.packageName)
|
||||||
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
|
?: Intent(appContext, MainActivity::class.java)
|
||||||
.setContentIntent(pendingIntent)
|
launchIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP)
|
||||||
.build()
|
val pendingIntent = PendingIntent.getActivity(
|
||||||
try {
|
appContext, 0, launchIntent,
|
||||||
NotificationManagerCompat.from(appContext).notify(email.hashCode(), notification)
|
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
|
||||||
} catch (error: SecurityException) {
|
)
|
||||||
android.util.Log.w(TAG, "Notification permission is unavailable", error)
|
val title = if (count == 1) "New mail" else "$count new messages"
|
||||||
}
|
val notification = NotificationCompat.Builder(appContext, MAIL_CHANNEL_ID)
|
||||||
}
|
.setSmallIcon(android.R.drawable.ic_dialog_email)
|
||||||
val update = JSONObject()
|
.setContentTitle(title)
|
||||||
.put("accountId", account.optString("id"))
|
.setContentText("Open ep-mail to check your inbox")
|
||||||
.put("newCount", count)
|
.setAutoCancel(true)
|
||||||
.put("foldersChanged", org.json.JSONArray().put("Inbox"))
|
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
|
||||||
appContext.sendBroadcast(Intent(ACTION_MAIL_SYNC)
|
.setContentIntent(pendingIntent)
|
||||||
.setPackage(appContext.packageName)
|
.build()
|
||||||
.putExtra(EXTRA_SYNC_UPDATE, update.toString()))
|
try {
|
||||||
}
|
NotificationManagerCompat.from(appContext).notify(email.hashCode(), notification)
|
||||||
|
} catch (error: SecurityException) {
|
||||||
fun notifySnoozeReminder(context: Context, account: JSONObject, reminder: JSONObject) {
|
android.util.Log.w(TAG, "Notification permission is unavailable (${error.javaClass.simpleName})")
|
||||||
val appContext = context.applicationContext
|
}
|
||||||
val email = account.optString("email")
|
}
|
||||||
if (account.optBoolean("notificationsEnabled", true)) {
|
val update = JSONObject()
|
||||||
val manager = appContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
|
.put("accountId", account.optString("id"))
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O &&
|
.put("newCount", count)
|
||||||
manager.getNotificationChannel(MAIL_CHANNEL_ID) == null) {
|
.put("foldersChanged", org.json.JSONArray().put("Inbox"))
|
||||||
manager.createNotificationChannel(NotificationChannel(
|
appContext.sendBroadcast(Intent(ACTION_MAIL_SYNC)
|
||||||
MAIL_CHANNEL_ID,
|
.setPackage(appContext.packageName)
|
||||||
"Mail reminders",
|
.putExtra(EXTRA_SYNC_UPDATE, update.toString()))
|
||||||
NotificationManager.IMPORTANCE_DEFAULT
|
}
|
||||||
))
|
|
||||||
}
|
fun notifySnoozeReminder(context: Context, account: JSONObject, reminder: JSONObject) {
|
||||||
val notification = NotificationCompat.Builder(appContext, MAIL_CHANNEL_ID)
|
val appContext = context.applicationContext
|
||||||
.setSmallIcon(android.R.drawable.ic_dialog_email)
|
val email = account.optString("email")
|
||||||
.setContentTitle("Mail reminder")
|
if (account.optBoolean("notificationsEnabled", true)) {
|
||||||
.setContentText(reminder.optString("subject").ifBlank { "A snoozed message is due" })
|
val manager = appContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
|
||||||
.setAutoCancel(true)
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O &&
|
||||||
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
|
manager.getNotificationChannel(MAIL_CHANNEL_ID) == null) {
|
||||||
.setContentIntent(appPendingIntentFor(appContext))
|
manager.createNotificationChannel(NotificationChannel(
|
||||||
.build()
|
MAIL_CHANNEL_ID,
|
||||||
try {
|
"Mail reminders",
|
||||||
NotificationManagerCompat.from(appContext).notify(
|
NotificationManager.IMPORTANCE_DEFAULT
|
||||||
(email + reminder.optLong("uid")).hashCode(),
|
))
|
||||||
notification
|
}
|
||||||
)
|
val notification = NotificationCompat.Builder(appContext, MAIL_CHANNEL_ID)
|
||||||
} catch (error: SecurityException) {
|
.setSmallIcon(android.R.drawable.ic_dialog_email)
|
||||||
android.util.Log.w(TAG, "Reminder notification permission is unavailable", error)
|
.setContentTitle("Mail reminder")
|
||||||
}
|
.setContentText("A snoozed message is due")
|
||||||
}
|
.setAutoCancel(true)
|
||||||
val update = JSONObject()
|
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
|
||||||
.put("accountId", account.optString("id"))
|
.setContentIntent(appPendingIntentFor(appContext))
|
||||||
.put("snoozeReminder", true)
|
.build()
|
||||||
.put("foldersChanged", org.json.JSONArray()
|
try {
|
||||||
.put("Snoozed")
|
NotificationManagerCompat.from(appContext).notify(
|
||||||
.put(reminder.optString("folder", "Inbox")))
|
(email + reminder.optLong("uid")).hashCode(),
|
||||||
appContext.sendBroadcast(Intent(ACTION_MAIL_SYNC)
|
notification
|
||||||
.setPackage(appContext.packageName)
|
)
|
||||||
.putExtra(EXTRA_SYNC_UPDATE, update.toString()))
|
} catch (error: SecurityException) {
|
||||||
}
|
android.util.Log.w(TAG, "Reminder notification permission is unavailable (${error.javaClass.simpleName})")
|
||||||
|
}
|
||||||
private fun appPendingIntentFor(context: Context): PendingIntent {
|
}
|
||||||
val intent = context.packageManager.getLaunchIntentForPackage(context.packageName)
|
val update = JSONObject()
|
||||||
?: Intent(context, MainActivity::class.java)
|
.put("accountId", account.optString("id"))
|
||||||
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP)
|
.put("snoozeReminder", true)
|
||||||
return PendingIntent.getActivity(
|
.put("foldersChanged", org.json.JSONArray()
|
||||||
context, 0, intent,
|
.put("Snoozed")
|
||||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
|
.put(reminder.optString("folder", "Inbox")))
|
||||||
)
|
appContext.sendBroadcast(Intent(ACTION_MAIL_SYNC)
|
||||||
}
|
.setPackage(appContext.packageName)
|
||||||
}
|
.putExtra(EXTRA_SYNC_UPDATE, update.toString()))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun appPendingIntentFor(context: Context): PendingIntent {
|
||||||
|
val intent = context.packageManager.getLaunchIntentForPackage(context.packageName)
|
||||||
|
?: Intent(context, MainActivity::class.java)
|
||||||
|
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP)
|
||||||
|
return PendingIntent.getActivity(
|
||||||
|
context, 0, intent,
|
||||||
|
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,19 +1,19 @@
|
|||||||
package studio.daybreak.mail;
|
package studio.daybreak.mail;
|
||||||
|
|
||||||
import android.Manifest;
|
import android.Manifest;
|
||||||
import android.content.pm.PackageManager;
|
import android.content.pm.PackageManager;
|
||||||
import android.os.Build;
|
import android.os.Build;
|
||||||
import android.os.Bundle;
|
import android.os.Bundle;
|
||||||
import androidx.core.app.ActivityCompat;
|
import androidx.core.app.ActivityCompat;
|
||||||
import com.getcapacitor.BridgeActivity;
|
import com.getcapacitor.BridgeActivity;
|
||||||
|
|
||||||
public class MainActivity extends BridgeActivity {
|
public class MainActivity extends BridgeActivity {
|
||||||
@Override
|
@Override
|
||||||
public void onCreate(Bundle savedInstanceState) {
|
public void onCreate(Bundle savedInstanceState) {
|
||||||
super.onCreate(savedInstanceState);
|
super.onCreate(savedInstanceState);
|
||||||
registerPlugin(EpMailPlugin.class);
|
registerPlugin(EpMailPlugin.class);
|
||||||
if (Build.VERSION.SDK_INT >= 33 && checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
|
if (Build.VERSION.SDK_INT >= 33 && checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
|
||||||
ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.POST_NOTIFICATIONS }, 701);
|
ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.POST_NOTIFICATIONS }, 701);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,34 +1,34 @@
|
|||||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
xmlns:aapt="http://schemas.android.com/aapt"
|
xmlns:aapt="http://schemas.android.com/aapt"
|
||||||
android:width="108dp"
|
android:width="108dp"
|
||||||
android:height="108dp"
|
android:height="108dp"
|
||||||
android:viewportHeight="108"
|
android:viewportHeight="108"
|
||||||
android:viewportWidth="108">
|
android:viewportWidth="108">
|
||||||
<path
|
<path
|
||||||
android:fillType="evenOdd"
|
android:fillType="evenOdd"
|
||||||
android:pathData="M32,64C32,64 38.39,52.99 44.13,50.95C51.37,48.37 70.14,49.57 70.14,49.57L108.26,87.69L108,109.01L75.97,107.97L32,64Z"
|
android:pathData="M32,64C32,64 38.39,52.99 44.13,50.95C51.37,48.37 70.14,49.57 70.14,49.57L108.26,87.69L108,109.01L75.97,107.97L32,64Z"
|
||||||
android:strokeColor="#00000000"
|
android:strokeColor="#00000000"
|
||||||
android:strokeWidth="1">
|
android:strokeWidth="1">
|
||||||
<aapt:attr name="android:fillColor">
|
<aapt:attr name="android:fillColor">
|
||||||
<gradient
|
<gradient
|
||||||
android:endX="78.5885"
|
android:endX="78.5885"
|
||||||
android:endY="90.9159"
|
android:endY="90.9159"
|
||||||
android:startX="48.7653"
|
android:startX="48.7653"
|
||||||
android:startY="61.0927"
|
android:startY="61.0927"
|
||||||
android:type="linear">
|
android:type="linear">
|
||||||
<item
|
<item
|
||||||
android:color="#44000000"
|
android:color="#44000000"
|
||||||
android:offset="0.0" />
|
android:offset="0.0" />
|
||||||
<item
|
<item
|
||||||
android:color="#00000000"
|
android:color="#00000000"
|
||||||
android:offset="1.0" />
|
android:offset="1.0" />
|
||||||
</gradient>
|
</gradient>
|
||||||
</aapt:attr>
|
</aapt:attr>
|
||||||
</path>
|
</path>
|
||||||
<path
|
<path
|
||||||
android:fillColor="#FFFFFF"
|
android:fillColor="#FFFFFF"
|
||||||
android:fillType="nonZero"
|
android:fillType="nonZero"
|
||||||
android:pathData="M66.94,46.02L66.94,46.02C72.44,50.07 76,56.61 76,64L32,64C32,56.61 35.56,50.11 40.98,46.06L36.18,41.19C35.45,40.45 35.45,39.3 36.18,38.56C36.91,37.81 38.05,37.81 38.78,38.56L44.25,44.05C47.18,42.57 50.48,41.71 54,41.71C57.48,41.71 60.78,42.57 63.68,44.05L69.11,38.56C69.84,37.81 70.98,37.81 71.71,38.56C72.44,39.3 72.44,40.45 71.71,41.19L66.94,46.02ZM62.94,56.92C64.08,56.92 65,56.01 65,54.88C65,53.76 64.08,52.85 62.94,52.85C61.8,52.85 60.88,53.76 60.88,54.88C60.88,56.01 61.8,56.92 62.94,56.92ZM45.06,56.92C46.2,56.92 47.13,56.01 47.13,54.88C47.13,53.76 46.2,52.85 45.06,52.85C43.92,52.85 43,53.76 43,54.88C43,56.01 43.92,56.92 45.06,56.92Z"
|
android:pathData="M66.94,46.02L66.94,46.02C72.44,50.07 76,56.61 76,64L32,64C32,56.61 35.56,50.11 40.98,46.06L36.18,41.19C35.45,40.45 35.45,39.3 36.18,38.56C36.91,37.81 38.05,37.81 38.78,38.56L44.25,44.05C47.18,42.57 50.48,41.71 54,41.71C57.48,41.71 60.78,42.57 63.68,44.05L69.11,38.56C69.84,37.81 70.98,37.81 71.71,38.56C72.44,39.3 72.44,40.45 71.71,41.19L66.94,46.02ZM62.94,56.92C64.08,56.92 65,56.01 65,54.88C65,53.76 64.08,52.85 62.94,52.85C61.8,52.85 60.88,53.76 60.88,54.88C60.88,56.01 61.8,56.92 62.94,56.92ZM45.06,56.92C46.2,56.92 47.13,56.01 47.13,54.88C47.13,53.76 46.2,52.85 45.06,52.85C43.92,52.85 43,53.76 43,54.88C43,56.01 43.92,56.92 45.06,56.92Z"
|
||||||
android:strokeColor="#00000000"
|
android:strokeColor="#00000000"
|
||||||
android:strokeWidth="1" />
|
android:strokeWidth="1" />
|
||||||
</vector>
|
</vector>
|
||||||
|
|||||||
@@ -1,170 +1,170 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
android:width="108dp"
|
android:width="108dp"
|
||||||
android:height="108dp"
|
android:height="108dp"
|
||||||
android:viewportHeight="108"
|
android:viewportHeight="108"
|
||||||
android:viewportWidth="108">
|
android:viewportWidth="108">
|
||||||
<path
|
<path
|
||||||
android:fillColor="#26A69A"
|
android:fillColor="#26A69A"
|
||||||
android:pathData="M0,0h108v108h-108z" />
|
android:pathData="M0,0h108v108h-108z" />
|
||||||
<path
|
<path
|
||||||
android:fillColor="#00000000"
|
android:fillColor="#00000000"
|
||||||
android:pathData="M9,0L9,108"
|
android:pathData="M9,0L9,108"
|
||||||
android:strokeColor="#33FFFFFF"
|
android:strokeColor="#33FFFFFF"
|
||||||
android:strokeWidth="0.8" />
|
android:strokeWidth="0.8" />
|
||||||
<path
|
<path
|
||||||
android:fillColor="#00000000"
|
android:fillColor="#00000000"
|
||||||
android:pathData="M19,0L19,108"
|
android:pathData="M19,0L19,108"
|
||||||
android:strokeColor="#33FFFFFF"
|
android:strokeColor="#33FFFFFF"
|
||||||
android:strokeWidth="0.8" />
|
android:strokeWidth="0.8" />
|
||||||
<path
|
<path
|
||||||
android:fillColor="#00000000"
|
android:fillColor="#00000000"
|
||||||
android:pathData="M29,0L29,108"
|
android:pathData="M29,0L29,108"
|
||||||
android:strokeColor="#33FFFFFF"
|
android:strokeColor="#33FFFFFF"
|
||||||
android:strokeWidth="0.8" />
|
android:strokeWidth="0.8" />
|
||||||
<path
|
<path
|
||||||
android:fillColor="#00000000"
|
android:fillColor="#00000000"
|
||||||
android:pathData="M39,0L39,108"
|
android:pathData="M39,0L39,108"
|
||||||
android:strokeColor="#33FFFFFF"
|
android:strokeColor="#33FFFFFF"
|
||||||
android:strokeWidth="0.8" />
|
android:strokeWidth="0.8" />
|
||||||
<path
|
<path
|
||||||
android:fillColor="#00000000"
|
android:fillColor="#00000000"
|
||||||
android:pathData="M49,0L49,108"
|
android:pathData="M49,0L49,108"
|
||||||
android:strokeColor="#33FFFFFF"
|
android:strokeColor="#33FFFFFF"
|
||||||
android:strokeWidth="0.8" />
|
android:strokeWidth="0.8" />
|
||||||
<path
|
<path
|
||||||
android:fillColor="#00000000"
|
android:fillColor="#00000000"
|
||||||
android:pathData="M59,0L59,108"
|
android:pathData="M59,0L59,108"
|
||||||
android:strokeColor="#33FFFFFF"
|
android:strokeColor="#33FFFFFF"
|
||||||
android:strokeWidth="0.8" />
|
android:strokeWidth="0.8" />
|
||||||
<path
|
<path
|
||||||
android:fillColor="#00000000"
|
android:fillColor="#00000000"
|
||||||
android:pathData="M69,0L69,108"
|
android:pathData="M69,0L69,108"
|
||||||
android:strokeColor="#33FFFFFF"
|
android:strokeColor="#33FFFFFF"
|
||||||
android:strokeWidth="0.8" />
|
android:strokeWidth="0.8" />
|
||||||
<path
|
<path
|
||||||
android:fillColor="#00000000"
|
android:fillColor="#00000000"
|
||||||
android:pathData="M79,0L79,108"
|
android:pathData="M79,0L79,108"
|
||||||
android:strokeColor="#33FFFFFF"
|
android:strokeColor="#33FFFFFF"
|
||||||
android:strokeWidth="0.8" />
|
android:strokeWidth="0.8" />
|
||||||
<path
|
<path
|
||||||
android:fillColor="#00000000"
|
android:fillColor="#00000000"
|
||||||
android:pathData="M89,0L89,108"
|
android:pathData="M89,0L89,108"
|
||||||
android:strokeColor="#33FFFFFF"
|
android:strokeColor="#33FFFFFF"
|
||||||
android:strokeWidth="0.8" />
|
android:strokeWidth="0.8" />
|
||||||
<path
|
<path
|
||||||
android:fillColor="#00000000"
|
android:fillColor="#00000000"
|
||||||
android:pathData="M99,0L99,108"
|
android:pathData="M99,0L99,108"
|
||||||
android:strokeColor="#33FFFFFF"
|
android:strokeColor="#33FFFFFF"
|
||||||
android:strokeWidth="0.8" />
|
android:strokeWidth="0.8" />
|
||||||
<path
|
<path
|
||||||
android:fillColor="#00000000"
|
android:fillColor="#00000000"
|
||||||
android:pathData="M0,9L108,9"
|
android:pathData="M0,9L108,9"
|
||||||
android:strokeColor="#33FFFFFF"
|
android:strokeColor="#33FFFFFF"
|
||||||
android:strokeWidth="0.8" />
|
android:strokeWidth="0.8" />
|
||||||
<path
|
<path
|
||||||
android:fillColor="#00000000"
|
android:fillColor="#00000000"
|
||||||
android:pathData="M0,19L108,19"
|
android:pathData="M0,19L108,19"
|
||||||
android:strokeColor="#33FFFFFF"
|
android:strokeColor="#33FFFFFF"
|
||||||
android:strokeWidth="0.8" />
|
android:strokeWidth="0.8" />
|
||||||
<path
|
<path
|
||||||
android:fillColor="#00000000"
|
android:fillColor="#00000000"
|
||||||
android:pathData="M0,29L108,29"
|
android:pathData="M0,29L108,29"
|
||||||
android:strokeColor="#33FFFFFF"
|
android:strokeColor="#33FFFFFF"
|
||||||
android:strokeWidth="0.8" />
|
android:strokeWidth="0.8" />
|
||||||
<path
|
<path
|
||||||
android:fillColor="#00000000"
|
android:fillColor="#00000000"
|
||||||
android:pathData="M0,39L108,39"
|
android:pathData="M0,39L108,39"
|
||||||
android:strokeColor="#33FFFFFF"
|
android:strokeColor="#33FFFFFF"
|
||||||
android:strokeWidth="0.8" />
|
android:strokeWidth="0.8" />
|
||||||
<path
|
<path
|
||||||
android:fillColor="#00000000"
|
android:fillColor="#00000000"
|
||||||
android:pathData="M0,49L108,49"
|
android:pathData="M0,49L108,49"
|
||||||
android:strokeColor="#33FFFFFF"
|
android:strokeColor="#33FFFFFF"
|
||||||
android:strokeWidth="0.8" />
|
android:strokeWidth="0.8" />
|
||||||
<path
|
<path
|
||||||
android:fillColor="#00000000"
|
android:fillColor="#00000000"
|
||||||
android:pathData="M0,59L108,59"
|
android:pathData="M0,59L108,59"
|
||||||
android:strokeColor="#33FFFFFF"
|
android:strokeColor="#33FFFFFF"
|
||||||
android:strokeWidth="0.8" />
|
android:strokeWidth="0.8" />
|
||||||
<path
|
<path
|
||||||
android:fillColor="#00000000"
|
android:fillColor="#00000000"
|
||||||
android:pathData="M0,69L108,69"
|
android:pathData="M0,69L108,69"
|
||||||
android:strokeColor="#33FFFFFF"
|
android:strokeColor="#33FFFFFF"
|
||||||
android:strokeWidth="0.8" />
|
android:strokeWidth="0.8" />
|
||||||
<path
|
<path
|
||||||
android:fillColor="#00000000"
|
android:fillColor="#00000000"
|
||||||
android:pathData="M0,79L108,79"
|
android:pathData="M0,79L108,79"
|
||||||
android:strokeColor="#33FFFFFF"
|
android:strokeColor="#33FFFFFF"
|
||||||
android:strokeWidth="0.8" />
|
android:strokeWidth="0.8" />
|
||||||
<path
|
<path
|
||||||
android:fillColor="#00000000"
|
android:fillColor="#00000000"
|
||||||
android:pathData="M0,89L108,89"
|
android:pathData="M0,89L108,89"
|
||||||
android:strokeColor="#33FFFFFF"
|
android:strokeColor="#33FFFFFF"
|
||||||
android:strokeWidth="0.8" />
|
android:strokeWidth="0.8" />
|
||||||
<path
|
<path
|
||||||
android:fillColor="#00000000"
|
android:fillColor="#00000000"
|
||||||
android:pathData="M0,99L108,99"
|
android:pathData="M0,99L108,99"
|
||||||
android:strokeColor="#33FFFFFF"
|
android:strokeColor="#33FFFFFF"
|
||||||
android:strokeWidth="0.8" />
|
android:strokeWidth="0.8" />
|
||||||
<path
|
<path
|
||||||
android:fillColor="#00000000"
|
android:fillColor="#00000000"
|
||||||
android:pathData="M19,29L89,29"
|
android:pathData="M19,29L89,29"
|
||||||
android:strokeColor="#33FFFFFF"
|
android:strokeColor="#33FFFFFF"
|
||||||
android:strokeWidth="0.8" />
|
android:strokeWidth="0.8" />
|
||||||
<path
|
<path
|
||||||
android:fillColor="#00000000"
|
android:fillColor="#00000000"
|
||||||
android:pathData="M19,39L89,39"
|
android:pathData="M19,39L89,39"
|
||||||
android:strokeColor="#33FFFFFF"
|
android:strokeColor="#33FFFFFF"
|
||||||
android:strokeWidth="0.8" />
|
android:strokeWidth="0.8" />
|
||||||
<path
|
<path
|
||||||
android:fillColor="#00000000"
|
android:fillColor="#00000000"
|
||||||
android:pathData="M19,49L89,49"
|
android:pathData="M19,49L89,49"
|
||||||
android:strokeColor="#33FFFFFF"
|
android:strokeColor="#33FFFFFF"
|
||||||
android:strokeWidth="0.8" />
|
android:strokeWidth="0.8" />
|
||||||
<path
|
<path
|
||||||
android:fillColor="#00000000"
|
android:fillColor="#00000000"
|
||||||
android:pathData="M19,59L89,59"
|
android:pathData="M19,59L89,59"
|
||||||
android:strokeColor="#33FFFFFF"
|
android:strokeColor="#33FFFFFF"
|
||||||
android:strokeWidth="0.8" />
|
android:strokeWidth="0.8" />
|
||||||
<path
|
<path
|
||||||
android:fillColor="#00000000"
|
android:fillColor="#00000000"
|
||||||
android:pathData="M19,69L89,69"
|
android:pathData="M19,69L89,69"
|
||||||
android:strokeColor="#33FFFFFF"
|
android:strokeColor="#33FFFFFF"
|
||||||
android:strokeWidth="0.8" />
|
android:strokeWidth="0.8" />
|
||||||
<path
|
<path
|
||||||
android:fillColor="#00000000"
|
android:fillColor="#00000000"
|
||||||
android:pathData="M19,79L89,79"
|
android:pathData="M19,79L89,79"
|
||||||
android:strokeColor="#33FFFFFF"
|
android:strokeColor="#33FFFFFF"
|
||||||
android:strokeWidth="0.8" />
|
android:strokeWidth="0.8" />
|
||||||
<path
|
<path
|
||||||
android:fillColor="#00000000"
|
android:fillColor="#00000000"
|
||||||
android:pathData="M29,19L29,89"
|
android:pathData="M29,19L29,89"
|
||||||
android:strokeColor="#33FFFFFF"
|
android:strokeColor="#33FFFFFF"
|
||||||
android:strokeWidth="0.8" />
|
android:strokeWidth="0.8" />
|
||||||
<path
|
<path
|
||||||
android:fillColor="#00000000"
|
android:fillColor="#00000000"
|
||||||
android:pathData="M39,19L39,89"
|
android:pathData="M39,19L39,89"
|
||||||
android:strokeColor="#33FFFFFF"
|
android:strokeColor="#33FFFFFF"
|
||||||
android:strokeWidth="0.8" />
|
android:strokeWidth="0.8" />
|
||||||
<path
|
<path
|
||||||
android:fillColor="#00000000"
|
android:fillColor="#00000000"
|
||||||
android:pathData="M49,19L49,89"
|
android:pathData="M49,19L49,89"
|
||||||
android:strokeColor="#33FFFFFF"
|
android:strokeColor="#33FFFFFF"
|
||||||
android:strokeWidth="0.8" />
|
android:strokeWidth="0.8" />
|
||||||
<path
|
<path
|
||||||
android:fillColor="#00000000"
|
android:fillColor="#00000000"
|
||||||
android:pathData="M59,19L59,89"
|
android:pathData="M59,19L59,89"
|
||||||
android:strokeColor="#33FFFFFF"
|
android:strokeColor="#33FFFFFF"
|
||||||
android:strokeWidth="0.8" />
|
android:strokeWidth="0.8" />
|
||||||
<path
|
<path
|
||||||
android:fillColor="#00000000"
|
android:fillColor="#00000000"
|
||||||
android:pathData="M69,19L69,89"
|
android:pathData="M69,19L69,89"
|
||||||
android:strokeColor="#33FFFFFF"
|
android:strokeColor="#33FFFFFF"
|
||||||
android:strokeWidth="0.8" />
|
android:strokeWidth="0.8" />
|
||||||
<path
|
<path
|
||||||
android:fillColor="#00000000"
|
android:fillColor="#00000000"
|
||||||
android:pathData="M79,19L79,89"
|
android:pathData="M79,19L79,89"
|
||||||
android:strokeColor="#33FFFFFF"
|
android:strokeColor="#33FFFFFF"
|
||||||
android:strokeWidth="0.8" />
|
android:strokeWidth="0.8" />
|
||||||
</vector>
|
</vector>
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
xmlns:app="http://schemas.android.com/apk/res-auto"
|
xmlns:app="http://schemas.android.com/apk/res-auto"
|
||||||
xmlns:tools="http://schemas.android.com/tools"
|
xmlns:tools="http://schemas.android.com/tools"
|
||||||
android:layout_width="match_parent"
|
android:layout_width="match_parent"
|
||||||
android:layout_height="match_parent"
|
android:layout_height="match_parent"
|
||||||
tools:context=".MainActivity">
|
tools:context=".MainActivity">
|
||||||
|
|
||||||
<WebView
|
<WebView
|
||||||
android:layout_width="match_parent"
|
android:layout_width="match_parent"
|
||||||
android:layout_height="match_parent" />
|
android:layout_height="match_parent" />
|
||||||
</androidx.coordinatorlayout.widget.CoordinatorLayout>
|
</androidx.coordinatorlayout.widget.CoordinatorLayout>
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
<background android:drawable="@color/ic_launcher_background"/>
|
<background android:drawable="@color/ic_launcher_background"/>
|
||||||
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
|
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
|
||||||
</adaptive-icon>
|
</adaptive-icon>
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
<background android:drawable="@color/ic_launcher_background"/>
|
<background android:drawable="@color/ic_launcher_background"/>
|
||||||
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
|
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
|
||||||
</adaptive-icon>
|
</adaptive-icon>
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
<resources>
|
<resources>
|
||||||
<color name="ic_launcher_background">#FFFFFF</color>
|
<color name="ic_launcher_background">#FFFFFF</color>
|
||||||
</resources>
|
</resources>
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
<?xml version='1.0' encoding='utf-8'?>
|
<?xml version='1.0' encoding='utf-8'?>
|
||||||
<resources>
|
<resources>
|
||||||
<string name="app_name">ep-mail</string>
|
<string name="app_name">ep-mail</string>
|
||||||
<string name="title_activity_main">ep-mail</string>
|
<string name="title_activity_main">ep-mail</string>
|
||||||
<string name="package_name">studio.daybreak.mail</string>
|
<string name="package_name">studio.daybreak.mail</string>
|
||||||
<string name="custom_url_scheme">studio.daybreak.mail</string>
|
<string name="custom_url_scheme">studio.daybreak.mail</string>
|
||||||
</resources>
|
</resources>
|
||||||
|
|||||||
@@ -1,22 +1,22 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
<resources>
|
<resources>
|
||||||
|
|
||||||
<!-- Base application theme. -->
|
<!-- Base application theme. -->
|
||||||
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
|
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
|
||||||
<!-- Customize your theme here. -->
|
<!-- Customize your theme here. -->
|
||||||
<item name="colorPrimary">@color/colorPrimary</item>
|
<item name="colorPrimary">@color/colorPrimary</item>
|
||||||
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
|
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
|
||||||
<item name="colorAccent">@color/colorAccent</item>
|
<item name="colorAccent">@color/colorAccent</item>
|
||||||
</style>
|
</style>
|
||||||
|
|
||||||
<style name="AppTheme.NoActionBar" parent="Theme.AppCompat.DayNight.NoActionBar">
|
<style name="AppTheme.NoActionBar" parent="Theme.AppCompat.DayNight.NoActionBar">
|
||||||
<item name="windowActionBar">false</item>
|
<item name="windowActionBar">false</item>
|
||||||
<item name="windowNoTitle">true</item>
|
<item name="windowNoTitle">true</item>
|
||||||
<item name="android:background">@null</item>
|
<item name="android:background">@null</item>
|
||||||
</style>
|
</style>
|
||||||
|
|
||||||
|
|
||||||
<style name="AppTheme.NoActionBarLaunch" parent="Theme.SplashScreen">
|
<style name="AppTheme.NoActionBarLaunch" parent="Theme.SplashScreen">
|
||||||
<item name="android:background">@drawable/splash</item>
|
<item name="android:background">@drawable/splash</item>
|
||||||
</style>
|
</style>
|
||||||
</resources>
|
</resources>
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<data-extraction-rules xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<cloud-backup>
|
||||||
|
<exclude domain="root" path="." />
|
||||||
|
<exclude domain="file" path="." />
|
||||||
|
<exclude domain="database" path="." />
|
||||||
|
<exclude domain="sharedpref" path="." />
|
||||||
|
<exclude domain="external" path="." />
|
||||||
|
</cloud-backup>
|
||||||
|
<device-transfer>
|
||||||
|
<exclude domain="root" path="." />
|
||||||
|
<exclude domain="file" path="." />
|
||||||
|
<exclude domain="database" path="." />
|
||||||
|
<exclude domain="sharedpref" path="." />
|
||||||
|
<exclude domain="external" path="." />
|
||||||
|
</device-transfer>
|
||||||
|
</data-extraction-rules>
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
|
||||||
<paths xmlns:android="http://schemas.android.com/apk/res/android">
|
|
||||||
<external-path name="my_images" path="." />
|
|
||||||
<cache-path name="my_cache_images" path="." />
|
|
||||||
</paths>
|
|
||||||
@@ -1,18 +1,18 @@
|
|||||||
package com.getcapacitor.myapp;
|
package com.getcapacitor.myapp;
|
||||||
|
|
||||||
import static org.junit.Assert.*;
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Example local unit test, which will execute on the development machine (host).
|
* Example local unit test, which will execute on the development machine (host).
|
||||||
*
|
*
|
||||||
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
|
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
|
||||||
*/
|
*/
|
||||||
public class ExampleUnitTest {
|
public class ExampleUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void addition_isCorrect() throws Exception {
|
public void addition_isCorrect() throws Exception {
|
||||||
assertEquals(4, 2 + 2);
|
assertEquals(4, 2 + 2);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
package studio.daybreak.mail
|
||||||
|
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class AttachmentNamePolicyTest {
|
||||||
|
@Test
|
||||||
|
fun stripsPathSeparatorsAndControlCharacters() {
|
||||||
|
assertEquals(".._secret.txt", AttachmentNamePolicy.sanitize("../secret.txt"))
|
||||||
|
assertEquals("folder__secret.txt", AttachmentNamePolicy.sanitize("folder\\/secret.txt"))
|
||||||
|
assertEquals("bad_name.txt", AttachmentNamePolicy.sanitize("bad\u0000name.txt"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun suppliesSafeFallbackAndBoundsLength() {
|
||||||
|
assertEquals("attachment", AttachmentNamePolicy.sanitize(".."))
|
||||||
|
assertEquals("attachment", AttachmentNamePolicy.sanitize(" "))
|
||||||
|
assertEquals(180, AttachmentNamePolicy.sanitize("a".repeat(300)).length)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
package studio.daybreak.mail
|
||||||
|
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertThrows
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class DavUrlPolicyTest {
|
||||||
|
@Test
|
||||||
|
fun acceptsHttpsServerUrl() {
|
||||||
|
assertEquals("https://dav.example.test/calendar", DavUrlPolicy.parseServerUrl(
|
||||||
|
"https://dav.example.test/calendar"
|
||||||
|
).toString())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun rejectsCleartextAndNonWebSchemes() {
|
||||||
|
assertThrows(IllegalArgumentException::class.java) {
|
||||||
|
DavUrlPolicy.parseServerUrl("http://localhost:8080/dav")
|
||||||
|
}
|
||||||
|
assertThrows(IllegalArgumentException::class.java) {
|
||||||
|
DavUrlPolicy.parseServerUrl("ftp://dav.example.test/dav")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun rejectsEmbeddedCredentialsAndFragments() {
|
||||||
|
assertThrows(IllegalArgumentException::class.java) {
|
||||||
|
DavUrlPolicy.parseServerUrl("https://user:pass@dav.example.test/dav")
|
||||||
|
}
|
||||||
|
assertThrows(IllegalArgumentException::class.java) {
|
||||||
|
DavUrlPolicy.parseServerUrl("https://dav.example.test/dav#fragment")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun allowsSameOriginAndRejectsCrossOriginTargets() {
|
||||||
|
DavUrlPolicy.requireSameOrigin(
|
||||||
|
"https://dav.example.test/root",
|
||||||
|
"https://dav.example.test/calendar/"
|
||||||
|
)
|
||||||
|
assertThrows(IllegalArgumentException::class.java) {
|
||||||
|
DavUrlPolicy.requireSameOrigin(
|
||||||
|
"https://dav.example.test/root",
|
||||||
|
"https://attacker.example.test/calendar/"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
assertThrows(IllegalArgumentException::class.java) {
|
||||||
|
DavUrlPolicy.requireSameOrigin(
|
||||||
|
"https://dav.example.test/root",
|
||||||
|
"http://dav.example.test/calendar/"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,30 +1,30 @@
|
|||||||
// Top-level build file where you can add configuration options common to all sub-projects/modules.
|
// Top-level build file where you can add configuration options common to all sub-projects/modules.
|
||||||
|
|
||||||
buildscript {
|
buildscript {
|
||||||
|
|
||||||
repositories {
|
repositories {
|
||||||
google()
|
google()
|
||||||
mavenCentral()
|
mavenCentral()
|
||||||
}
|
}
|
||||||
dependencies {
|
dependencies {
|
||||||
classpath 'com.android.tools.build:gradle:8.13.0'
|
classpath 'com.android.tools.build:gradle:8.13.0'
|
||||||
classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:2.0.21'
|
classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:2.0.21'
|
||||||
classpath 'com.google.gms:google-services:4.4.4'
|
classpath 'com.google.gms:google-services:4.4.4'
|
||||||
|
|
||||||
// NOTE: Do not place your application dependencies here; they belong
|
// NOTE: Do not place your application dependencies here; they belong
|
||||||
// in the individual module build.gradle files
|
// in the individual module build.gradle files
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
apply from: "variables.gradle"
|
apply from: "variables.gradle"
|
||||||
|
|
||||||
allprojects {
|
allprojects {
|
||||||
repositories {
|
repositories {
|
||||||
google()
|
google()
|
||||||
mavenCentral()
|
mavenCentral()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
task clean(type: Delete) {
|
task clean(type: Delete) {
|
||||||
delete rootProject.buildDir
|
delete rootProject.buildDir
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,22 +1,22 @@
|
|||||||
# Project-wide Gradle settings.
|
# Project-wide Gradle settings.
|
||||||
|
|
||||||
# IDE (e.g. Android Studio) users:
|
# IDE (e.g. Android Studio) users:
|
||||||
# Gradle settings configured through the IDE *will override*
|
# Gradle settings configured through the IDE *will override*
|
||||||
# any settings specified in this file.
|
# any settings specified in this file.
|
||||||
|
|
||||||
# For more details on how to configure your build environment visit
|
# For more details on how to configure your build environment visit
|
||||||
# http://www.gradle.org/docs/current/userguide/build_environment.html
|
# http://www.gradle.org/docs/current/userguide/build_environment.html
|
||||||
|
|
||||||
# Specifies the JVM arguments used for the daemon process.
|
# Specifies the JVM arguments used for the daemon process.
|
||||||
# The setting is particularly useful for tweaking memory settings.
|
# The setting is particularly useful for tweaking memory settings.
|
||||||
org.gradle.jvmargs=-Xmx1536m
|
org.gradle.jvmargs=-Xmx1536m
|
||||||
|
|
||||||
# When configured, Gradle will run in incubating parallel mode.
|
# When configured, Gradle will run in incubating parallel mode.
|
||||||
# This option should only be used with decoupled projects. More details, visit
|
# This option should only be used with decoupled projects. More details, visit
|
||||||
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
|
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
|
||||||
# org.gradle.parallel=true
|
# org.gradle.parallel=true
|
||||||
|
|
||||||
# AndroidX package structure to make it clearer which packages are bundled with the
|
# AndroidX package structure to make it clearer which packages are bundled with the
|
||||||
# Android operating system, and which are packaged with your app's APK
|
# Android operating system, and which are packaged with your app's APK
|
||||||
# https://developer.android.com/topic/libraries/support-library/androidx-rn
|
# https://developer.android.com/topic/libraries/support-library/androidx-rn
|
||||||
android.useAndroidX=true
|
android.useAndroidX=true
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
distributionBase=GRADLE_USER_HOME
|
distributionBase=GRADLE_USER_HOME
|
||||||
distributionPath=wrapper/dists
|
distributionPath=wrapper/dists
|
||||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-all.zip
|
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-all.zip
|
||||||
networkTimeout=10000
|
networkTimeout=10000
|
||||||
validateDistributionUrl=true
|
validateDistributionUrl=true
|
||||||
zipStoreBase=GRADLE_USER_HOME
|
zipStoreBase=GRADLE_USER_HOME
|
||||||
zipStorePath=wrapper/dists
|
zipStorePath=wrapper/dists
|
||||||
|
|||||||
@@ -1,251 +1,251 @@
|
|||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
|
|
||||||
#
|
#
|
||||||
# Copyright © 2015-2021 the original authors.
|
# Copyright © 2015-2021 the original authors.
|
||||||
#
|
#
|
||||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
# you may not use this file except in compliance with the License.
|
# you may not use this file except in compliance with the License.
|
||||||
# You may obtain a copy of the License at
|
# You may obtain a copy of the License at
|
||||||
#
|
#
|
||||||
# https://www.apache.org/licenses/LICENSE-2.0
|
# https://www.apache.org/licenses/LICENSE-2.0
|
||||||
#
|
#
|
||||||
# Unless required by applicable law or agreed to in writing, software
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
# See the License for the specific language governing permissions and
|
# See the License for the specific language governing permissions and
|
||||||
# limitations under the License.
|
# limitations under the License.
|
||||||
#
|
#
|
||||||
# SPDX-License-Identifier: Apache-2.0
|
# SPDX-License-Identifier: Apache-2.0
|
||||||
#
|
#
|
||||||
|
|
||||||
##############################################################################
|
##############################################################################
|
||||||
#
|
#
|
||||||
# Gradle start up script for POSIX generated by Gradle.
|
# Gradle start up script for POSIX generated by Gradle.
|
||||||
#
|
#
|
||||||
# Important for running:
|
# Important for running:
|
||||||
#
|
#
|
||||||
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||||
# noncompliant, but you have some other compliant shell such as ksh or
|
# noncompliant, but you have some other compliant shell such as ksh or
|
||||||
# bash, then to run this script, type that shell name before the whole
|
# bash, then to run this script, type that shell name before the whole
|
||||||
# command line, like:
|
# command line, like:
|
||||||
#
|
#
|
||||||
# ksh Gradle
|
# ksh Gradle
|
||||||
#
|
#
|
||||||
# Busybox and similar reduced shells will NOT work, because this script
|
# Busybox and similar reduced shells will NOT work, because this script
|
||||||
# requires all of these POSIX shell features:
|
# requires all of these POSIX shell features:
|
||||||
# * functions;
|
# * functions;
|
||||||
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||||
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||||
# * compound commands having a testable exit status, especially «case»;
|
# * compound commands having a testable exit status, especially «case»;
|
||||||
# * various built-in commands including «command», «set», and «ulimit».
|
# * various built-in commands including «command», «set», and «ulimit».
|
||||||
#
|
#
|
||||||
# Important for patching:
|
# Important for patching:
|
||||||
#
|
#
|
||||||
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||||
# by Bash, Ksh, etc; in particular arrays are avoided.
|
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||||
#
|
#
|
||||||
# The "traditional" practice of packing multiple parameters into a
|
# The "traditional" practice of packing multiple parameters into a
|
||||||
# space-separated string is a well documented source of bugs and security
|
# space-separated string is a well documented source of bugs and security
|
||||||
# problems, so this is (mostly) avoided, by progressively accumulating
|
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||||
# options in "$@", and eventually passing that to Java.
|
# options in "$@", and eventually passing that to Java.
|
||||||
#
|
#
|
||||||
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||||
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||||
# see the in-line comments for details.
|
# see the in-line comments for details.
|
||||||
#
|
#
|
||||||
# There are tweaks for specific operating systems such as AIX, CygWin,
|
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||||
# Darwin, MinGW, and NonStop.
|
# Darwin, MinGW, and NonStop.
|
||||||
#
|
#
|
||||||
# (3) This script is generated from the Groovy template
|
# (3) This script is generated from the Groovy template
|
||||||
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||||
# within the Gradle project.
|
# within the Gradle project.
|
||||||
#
|
#
|
||||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||||
#
|
#
|
||||||
##############################################################################
|
##############################################################################
|
||||||
|
|
||||||
# Attempt to set APP_HOME
|
# Attempt to set APP_HOME
|
||||||
|
|
||||||
# Resolve links: $0 may be a link
|
# Resolve links: $0 may be a link
|
||||||
app_path=$0
|
app_path=$0
|
||||||
|
|
||||||
# Need this for daisy-chained symlinks.
|
# Need this for daisy-chained symlinks.
|
||||||
while
|
while
|
||||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||||
[ -h "$app_path" ]
|
[ -h "$app_path" ]
|
||||||
do
|
do
|
||||||
ls=$( ls -ld "$app_path" )
|
ls=$( ls -ld "$app_path" )
|
||||||
link=${ls#*' -> '}
|
link=${ls#*' -> '}
|
||||||
case $link in #(
|
case $link in #(
|
||||||
/*) app_path=$link ;; #(
|
/*) app_path=$link ;; #(
|
||||||
*) app_path=$APP_HOME$link ;;
|
*) app_path=$APP_HOME$link ;;
|
||||||
esac
|
esac
|
||||||
done
|
done
|
||||||
|
|
||||||
# This is normally unused
|
# This is normally unused
|
||||||
# shellcheck disable=SC2034
|
# shellcheck disable=SC2034
|
||||||
APP_BASE_NAME=${0##*/}
|
APP_BASE_NAME=${0##*/}
|
||||||
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||||
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
|
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
|
||||||
|
|
||||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||||
MAX_FD=maximum
|
MAX_FD=maximum
|
||||||
|
|
||||||
warn () {
|
warn () {
|
||||||
echo "$*"
|
echo "$*"
|
||||||
} >&2
|
} >&2
|
||||||
|
|
||||||
die () {
|
die () {
|
||||||
echo
|
echo
|
||||||
echo "$*"
|
echo "$*"
|
||||||
echo
|
echo
|
||||||
exit 1
|
exit 1
|
||||||
} >&2
|
} >&2
|
||||||
|
|
||||||
# OS specific support (must be 'true' or 'false').
|
# OS specific support (must be 'true' or 'false').
|
||||||
cygwin=false
|
cygwin=false
|
||||||
msys=false
|
msys=false
|
||||||
darwin=false
|
darwin=false
|
||||||
nonstop=false
|
nonstop=false
|
||||||
case "$( uname )" in #(
|
case "$( uname )" in #(
|
||||||
CYGWIN* ) cygwin=true ;; #(
|
CYGWIN* ) cygwin=true ;; #(
|
||||||
Darwin* ) darwin=true ;; #(
|
Darwin* ) darwin=true ;; #(
|
||||||
MSYS* | MINGW* ) msys=true ;; #(
|
MSYS* | MINGW* ) msys=true ;; #(
|
||||||
NONSTOP* ) nonstop=true ;;
|
NONSTOP* ) nonstop=true ;;
|
||||||
esac
|
esac
|
||||||
|
|
||||||
CLASSPATH="\\\"\\\""
|
CLASSPATH="\\\"\\\""
|
||||||
|
|
||||||
|
|
||||||
# Determine the Java command to use to start the JVM.
|
# Determine the Java command to use to start the JVM.
|
||||||
if [ -n "$JAVA_HOME" ] ; then
|
if [ -n "$JAVA_HOME" ] ; then
|
||||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||||
# IBM's JDK on AIX uses strange locations for the executables
|
# IBM's JDK on AIX uses strange locations for the executables
|
||||||
JAVACMD=$JAVA_HOME/jre/sh/java
|
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||||
else
|
else
|
||||||
JAVACMD=$JAVA_HOME/bin/java
|
JAVACMD=$JAVA_HOME/bin/java
|
||||||
fi
|
fi
|
||||||
if [ ! -x "$JAVACMD" ] ; then
|
if [ ! -x "$JAVACMD" ] ; then
|
||||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||||
|
|
||||||
Please set the JAVA_HOME variable in your environment to match the
|
Please set the JAVA_HOME variable in your environment to match the
|
||||||
location of your Java installation."
|
location of your Java installation."
|
||||||
fi
|
fi
|
||||||
else
|
else
|
||||||
JAVACMD=java
|
JAVACMD=java
|
||||||
if ! command -v java >/dev/null 2>&1
|
if ! command -v java >/dev/null 2>&1
|
||||||
then
|
then
|
||||||
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||||
|
|
||||||
Please set the JAVA_HOME variable in your environment to match the
|
Please set the JAVA_HOME variable in your environment to match the
|
||||||
location of your Java installation."
|
location of your Java installation."
|
||||||
fi
|
fi
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Increase the maximum file descriptors if we can.
|
# Increase the maximum file descriptors if we can.
|
||||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||||
case $MAX_FD in #(
|
case $MAX_FD in #(
|
||||||
max*)
|
max*)
|
||||||
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||||
# shellcheck disable=SC2039,SC3045
|
# shellcheck disable=SC2039,SC3045
|
||||||
MAX_FD=$( ulimit -H -n ) ||
|
MAX_FD=$( ulimit -H -n ) ||
|
||||||
warn "Could not query maximum file descriptor limit"
|
warn "Could not query maximum file descriptor limit"
|
||||||
esac
|
esac
|
||||||
case $MAX_FD in #(
|
case $MAX_FD in #(
|
||||||
'' | soft) :;; #(
|
'' | soft) :;; #(
|
||||||
*)
|
*)
|
||||||
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||||
# shellcheck disable=SC2039,SC3045
|
# shellcheck disable=SC2039,SC3045
|
||||||
ulimit -n "$MAX_FD" ||
|
ulimit -n "$MAX_FD" ||
|
||||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||||
esac
|
esac
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Collect all arguments for the java command, stacking in reverse order:
|
# Collect all arguments for the java command, stacking in reverse order:
|
||||||
# * args from the command line
|
# * args from the command line
|
||||||
# * the main class name
|
# * the main class name
|
||||||
# * -classpath
|
# * -classpath
|
||||||
# * -D...appname settings
|
# * -D...appname settings
|
||||||
# * --module-path (only if needed)
|
# * --module-path (only if needed)
|
||||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||||
|
|
||||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||||
if "$cygwin" || "$msys" ; then
|
if "$cygwin" || "$msys" ; then
|
||||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||||
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
||||||
|
|
||||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||||
|
|
||||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||||
for arg do
|
for arg do
|
||||||
if
|
if
|
||||||
case $arg in #(
|
case $arg in #(
|
||||||
-*) false ;; # don't mess with options #(
|
-*) false ;; # don't mess with options #(
|
||||||
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||||
[ -e "$t" ] ;; #(
|
[ -e "$t" ] ;; #(
|
||||||
*) false ;;
|
*) false ;;
|
||||||
esac
|
esac
|
||||||
then
|
then
|
||||||
arg=$( cygpath --path --ignore --mixed "$arg" )
|
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||||
fi
|
fi
|
||||||
# Roll the args list around exactly as many times as the number of
|
# Roll the args list around exactly as many times as the number of
|
||||||
# args, so each arg winds up back in the position where it started, but
|
# args, so each arg winds up back in the position where it started, but
|
||||||
# possibly modified.
|
# possibly modified.
|
||||||
#
|
#
|
||||||
# NB: a `for` loop captures its iteration list before it begins, so
|
# NB: a `for` loop captures its iteration list before it begins, so
|
||||||
# changing the positional parameters here affects neither the number of
|
# changing the positional parameters here affects neither the number of
|
||||||
# iterations, nor the values presented in `arg`.
|
# iterations, nor the values presented in `arg`.
|
||||||
shift # remove old arg
|
shift # remove old arg
|
||||||
set -- "$@" "$arg" # push replacement arg
|
set -- "$@" "$arg" # push replacement arg
|
||||||
done
|
done
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
|
||||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||||
|
|
||||||
# Collect all arguments for the java command:
|
# Collect all arguments for the java command:
|
||||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||||
# and any embedded shellness will be escaped.
|
# and any embedded shellness will be escaped.
|
||||||
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||||
# treated as '${Hostname}' itself on the command line.
|
# treated as '${Hostname}' itself on the command line.
|
||||||
|
|
||||||
set -- \
|
set -- \
|
||||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||||
-classpath "$CLASSPATH" \
|
-classpath "$CLASSPATH" \
|
||||||
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
|
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
|
||||||
"$@"
|
"$@"
|
||||||
|
|
||||||
# Stop when "xargs" is not available.
|
# Stop when "xargs" is not available.
|
||||||
if ! command -v xargs >/dev/null 2>&1
|
if ! command -v xargs >/dev/null 2>&1
|
||||||
then
|
then
|
||||||
die "xargs is not available"
|
die "xargs is not available"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Use "xargs" to parse quoted args.
|
# Use "xargs" to parse quoted args.
|
||||||
#
|
#
|
||||||
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||||
#
|
#
|
||||||
# In Bash we could simply go:
|
# In Bash we could simply go:
|
||||||
#
|
#
|
||||||
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||||
# set -- "${ARGS[@]}" "$@"
|
# set -- "${ARGS[@]}" "$@"
|
||||||
#
|
#
|
||||||
# but POSIX shell has neither arrays nor command substitution, so instead we
|
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||||
# post-process each arg (as a line of input to sed) to backslash-escape any
|
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||||
# character that might be a shell metacharacter, then use eval to reverse
|
# character that might be a shell metacharacter, then use eval to reverse
|
||||||
# that process (while maintaining the separation between arguments), and wrap
|
# that process (while maintaining the separation between arguments), and wrap
|
||||||
# the whole thing up as a single "set" statement.
|
# the whole thing up as a single "set" statement.
|
||||||
#
|
#
|
||||||
# This will of course break if any of these variables contains a newline or
|
# This will of course break if any of these variables contains a newline or
|
||||||
# an unmatched quote.
|
# an unmatched quote.
|
||||||
#
|
#
|
||||||
|
|
||||||
eval "set -- $(
|
eval "set -- $(
|
||||||
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||||
xargs -n1 |
|
xargs -n1 |
|
||||||
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||||
tr '\n' ' '
|
tr '\n' ' '
|
||||||
)" '"$@"'
|
)" '"$@"'
|
||||||
|
|
||||||
exec "$JAVACMD" "$@"
|
exec "$JAVACMD" "$@"
|
||||||
|
|||||||
@@ -1,94 +1,94 @@
|
|||||||
@rem
|
@rem
|
||||||
@rem Copyright 2015 the original author or authors.
|
@rem Copyright 2015 the original author or authors.
|
||||||
@rem
|
@rem
|
||||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
@rem you may not use this file except in compliance with the License.
|
@rem you may not use this file except in compliance with the License.
|
||||||
@rem You may obtain a copy of the License at
|
@rem You may obtain a copy of the License at
|
||||||
@rem
|
@rem
|
||||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||||
@rem
|
@rem
|
||||||
@rem Unless required by applicable law or agreed to in writing, software
|
@rem Unless required by applicable law or agreed to in writing, software
|
||||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
@rem See the License for the specific language governing permissions and
|
@rem See the License for the specific language governing permissions and
|
||||||
@rem limitations under the License.
|
@rem limitations under the License.
|
||||||
@rem
|
@rem
|
||||||
@rem SPDX-License-Identifier: Apache-2.0
|
@rem SPDX-License-Identifier: Apache-2.0
|
||||||
@rem
|
@rem
|
||||||
|
|
||||||
@if "%DEBUG%"=="" @echo off
|
@if "%DEBUG%"=="" @echo off
|
||||||
@rem ##########################################################################
|
@rem ##########################################################################
|
||||||
@rem
|
@rem
|
||||||
@rem Gradle startup script for Windows
|
@rem Gradle startup script for Windows
|
||||||
@rem
|
@rem
|
||||||
@rem ##########################################################################
|
@rem ##########################################################################
|
||||||
|
|
||||||
@rem Set local scope for the variables with windows NT shell
|
@rem Set local scope for the variables with windows NT shell
|
||||||
if "%OS%"=="Windows_NT" setlocal
|
if "%OS%"=="Windows_NT" setlocal
|
||||||
|
|
||||||
set DIRNAME=%~dp0
|
set DIRNAME=%~dp0
|
||||||
if "%DIRNAME%"=="" set DIRNAME=.
|
if "%DIRNAME%"=="" set DIRNAME=.
|
||||||
@rem This is normally unused
|
@rem This is normally unused
|
||||||
set APP_BASE_NAME=%~n0
|
set APP_BASE_NAME=%~n0
|
||||||
set APP_HOME=%DIRNAME%
|
set APP_HOME=%DIRNAME%
|
||||||
|
|
||||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||||
|
|
||||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||||
|
|
||||||
@rem Find java.exe
|
@rem Find java.exe
|
||||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||||
|
|
||||||
set JAVA_EXE=java.exe
|
set JAVA_EXE=java.exe
|
||||||
%JAVA_EXE% -version >NUL 2>&1
|
%JAVA_EXE% -version >NUL 2>&1
|
||||||
if %ERRORLEVEL% equ 0 goto execute
|
if %ERRORLEVEL% equ 0 goto execute
|
||||||
|
|
||||||
echo. 1>&2
|
echo. 1>&2
|
||||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
|
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
|
||||||
echo. 1>&2
|
echo. 1>&2
|
||||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||||
echo location of your Java installation. 1>&2
|
echo location of your Java installation. 1>&2
|
||||||
|
|
||||||
goto fail
|
goto fail
|
||||||
|
|
||||||
:findJavaFromJavaHome
|
:findJavaFromJavaHome
|
||||||
set JAVA_HOME=%JAVA_HOME:"=%
|
set JAVA_HOME=%JAVA_HOME:"=%
|
||||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||||
|
|
||||||
if exist "%JAVA_EXE%" goto execute
|
if exist "%JAVA_EXE%" goto execute
|
||||||
|
|
||||||
echo. 1>&2
|
echo. 1>&2
|
||||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
|
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
|
||||||
echo. 1>&2
|
echo. 1>&2
|
||||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||||
echo location of your Java installation. 1>&2
|
echo location of your Java installation. 1>&2
|
||||||
|
|
||||||
goto fail
|
goto fail
|
||||||
|
|
||||||
:execute
|
:execute
|
||||||
@rem Setup the command line
|
@rem Setup the command line
|
||||||
|
|
||||||
set CLASSPATH=
|
set CLASSPATH=
|
||||||
|
|
||||||
|
|
||||||
@rem Execute Gradle
|
@rem Execute Gradle
|
||||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
|
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
|
||||||
|
|
||||||
:end
|
:end
|
||||||
@rem End local scope for the variables with windows NT shell
|
@rem End local scope for the variables with windows NT shell
|
||||||
if %ERRORLEVEL% equ 0 goto mainEnd
|
if %ERRORLEVEL% equ 0 goto mainEnd
|
||||||
|
|
||||||
:fail
|
:fail
|
||||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||||
rem the _cmd.exe /c_ return code!
|
rem the _cmd.exe /c_ return code!
|
||||||
set EXIT_CODE=%ERRORLEVEL%
|
set EXIT_CODE=%ERRORLEVEL%
|
||||||
if %EXIT_CODE% equ 0 set EXIT_CODE=1
|
if %EXIT_CODE% equ 0 set EXIT_CODE=1
|
||||||
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
|
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
|
||||||
exit /b %EXIT_CODE%
|
exit /b %EXIT_CODE%
|
||||||
|
|
||||||
:mainEnd
|
:mainEnd
|
||||||
if "%OS%"=="Windows_NT" endlocal
|
if "%OS%"=="Windows_NT" endlocal
|
||||||
|
|
||||||
:omega
|
:omega
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
include ':app'
|
include ':app'
|
||||||
include ':capacitor-cordova-android-plugins'
|
include ':capacitor-cordova-android-plugins'
|
||||||
project(':capacitor-cordova-android-plugins').projectDir = new File('./capacitor-cordova-android-plugins/')
|
project(':capacitor-cordova-android-plugins').projectDir = new File('./capacitor-cordova-android-plugins/')
|
||||||
|
|
||||||
apply from: 'capacitor.settings.gradle'
|
apply from: 'capacitor.settings.gradle'
|
||||||
@@ -1,16 +1,16 @@
|
|||||||
ext {
|
ext {
|
||||||
minSdkVersion = 24
|
minSdkVersion = 24
|
||||||
compileSdkVersion = 36
|
compileSdkVersion = 36
|
||||||
targetSdkVersion = 36
|
targetSdkVersion = 36
|
||||||
androidxActivityVersion = '1.11.0'
|
androidxActivityVersion = '1.11.0'
|
||||||
androidxAppCompatVersion = '1.7.1'
|
androidxAppCompatVersion = '1.7.1'
|
||||||
androidxCoordinatorLayoutVersion = '1.3.0'
|
androidxCoordinatorLayoutVersion = '1.3.0'
|
||||||
androidxCoreVersion = '1.17.0'
|
androidxCoreVersion = '1.17.0'
|
||||||
androidxFragmentVersion = '1.8.9'
|
androidxFragmentVersion = '1.8.9'
|
||||||
coreSplashScreenVersion = '1.2.0'
|
coreSplashScreenVersion = '1.2.0'
|
||||||
androidxWebkitVersion = '1.14.0'
|
androidxWebkitVersion = '1.14.0'
|
||||||
junitVersion = '4.13.2'
|
junitVersion = '4.13.2'
|
||||||
androidxJunitVersion = '1.3.0'
|
androidxJunitVersion = '1.3.0'
|
||||||
androidxEspressoCoreVersion = '3.7.0'
|
androidxEspressoCoreVersion = '3.7.0'
|
||||||
cordovaAndroidVersion = '14.0.1'
|
cordovaAndroidVersion = '14.0.1'
|
||||||
}
|
}
|
||||||
@@ -2,40 +2,40 @@
|
|||||||
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 state = window.epMailState;
|
const state = window.epMailState;
|
||||||
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]))}
|
||||||
const { safeRemoteImageUrl, sanitizeMailHtml } = window.epMailFeatures.contentSecurity;
|
const { safeRemoteImageUrl, sanitizeMailHtml } = window.epMailFeatures.contentSecurity;
|
||||||
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 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){
|
function openMessage(id){
|
||||||
state.activeMessage=id;
|
state.activeMessage=id;
|
||||||
const m=state.messages.find(x=>x.id===id);
|
const m=state.messages.find(x=>x.id===id);
|
||||||
if(!m)return;
|
if(!m)return;
|
||||||
m.unread=false;
|
m.unread=false;
|
||||||
renderList();
|
renderList();
|
||||||
let safeHtml={html:'',remoteImageCount:0};
|
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)}
|
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 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 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('');
|
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>`;
|
$('#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',()=>{
|
$('#load-remote-images')?.addEventListener('click',()=>{
|
||||||
$('#reader-pane').querySelectorAll('.reader-body img[data-remote-src]').forEach(image=>{
|
$('#reader-pane').querySelectorAll('.reader-body img[data-remote-src]').forEach(image=>{
|
||||||
const url=safeRemoteImageUrl(image.getAttribute('data-remote-src'));
|
const url=safeRemoteImageUrl(image.getAttribute('data-remote-src'));
|
||||||
image.removeAttribute('data-remote-src');
|
image.removeAttribute('data-remote-src');
|
||||||
if(url)image.src=url;
|
if(url)image.src=url;
|
||||||
});
|
});
|
||||||
$('.remote-image-notice')?.remove();
|
$('.remote-image-notice')?.remove();
|
||||||
});
|
});
|
||||||
$('#reader-archive').onclick=()=>{m.archived=true;toast('Moved to Archive');renderList();$('#reader-pane').innerHTML=emptyReader()};
|
$('#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-delete').onclick=()=>{m.deleted=true;toast('Moved to Trash');renderList();$('#reader-pane').innerHTML=emptyReader()};
|
||||||
$('#reader-star').onclick=()=>{m.star=!m.star;renderList();openMessage(id)};
|
$('#reader-star').onclick=()=>{m.star=!m.star;renderList();openMessage(id)};
|
||||||
$('#reply').onclick=()=>showCompose(m);
|
$('#reply').onclick=()=>showCompose(m);
|
||||||
$('#forward').onclick=()=>showCompose(m,true);
|
$('#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(state.toastTimer);state.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;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 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){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 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();}
|
||||||
$$('.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);
|
$$('.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);
|
||||||
|
|
||||||
window.epMailShell = Object.freeze({
|
window.epMailShell = Object.freeze({
|
||||||
state,
|
state,
|
||||||
|
|||||||
@@ -5,159 +5,159 @@ const selectAttachmentUi = attachmentMailUi.select;
|
|||||||
const selectAllAttachmentUi = attachmentMailUi.selectAll;
|
const selectAllAttachmentUi = attachmentMailUi.selectAll;
|
||||||
const toastAttachmentUi = attachmentMailUi.toast;
|
const toastAttachmentUi = attachmentMailUi.toast;
|
||||||
const attachmentFolders = ['Inbox', 'Sent', 'Archive', 'Trash'];
|
const attachmentFolders = ['Inbox', 'Sent', 'Archive', 'Trash'];
|
||||||
let attachmentItems = [];
|
let attachmentItems = [];
|
||||||
|
|
||||||
function attachmentKind(filename) {
|
function attachmentKind(filename) {
|
||||||
const ext = String(filename).toLowerCase().split('.').pop();
|
const ext = String(filename).toLowerCase().split('.').pop();
|
||||||
if (['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'svg'].includes(ext)) return 'Images';
|
if (['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'svg'].includes(ext)) return 'Images';
|
||||||
if (['pdf', 'doc', 'docx', 'odt', 'txt', 'rtf', 'md', 'xls', 'xlsx', 'csv', 'ppt', 'pptx'].includes(ext)) return 'Documents';
|
if (['pdf', 'doc', 'docx', 'odt', 'txt', 'rtf', 'md', 'xls', 'xlsx', 'csv', 'ppt', 'pptx'].includes(ext)) return 'Documents';
|
||||||
if (['zip', 'rar', '7z', 'tar', 'gz'].includes(ext)) return 'Archives';
|
if (['zip', 'rar', '7z', 'tar', 'gz'].includes(ext)) return 'Archives';
|
||||||
return 'Other';
|
return 'Other';
|
||||||
}
|
}
|
||||||
|
|
||||||
function attachmentSize(size) {
|
function attachmentSize(size) {
|
||||||
if (!size) return '';
|
if (!size) return '';
|
||||||
if (typeof size === 'string') return size;
|
if (typeof size === 'string') return size;
|
||||||
return size < 1048576 ? `${Math.max(1, Math.round(size / 1024))} KB` : `${(size / 1048576).toFixed(1)} MB`;
|
return size < 1048576 ? `${Math.max(1, Math.round(size / 1024))} KB` : `${(size / 1048576).toFixed(1)} MB`;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function previewAttachment(target, details) {
|
async function previewAttachment(target, details) {
|
||||||
if (!details.uid || !window.daybreakMail?.previewAttachment) {
|
if (!details.uid || !window.daybreakMail?.previewAttachment) {
|
||||||
target.textContent = 'Previews are available for connected mailbox messages.';
|
target.textContent = 'Previews are available for connected mailbox messages.';
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
target.textContent = 'Loading preview…';
|
target.textContent = 'Loading preview…';
|
||||||
try {
|
try {
|
||||||
const result = await window.daybreakMail.previewAttachment(details);
|
const result = await window.daybreakMail.previewAttachment(details);
|
||||||
target.replaceChildren();
|
target.replaceChildren();
|
||||||
if (result.kind === 'image') {
|
if (result.kind === 'image') {
|
||||||
const image = document.createElement('img');
|
const image = document.createElement('img');
|
||||||
image.className = 'attachment-preview-image';
|
image.className = 'attachment-preview-image';
|
||||||
image.alt = details.filename;
|
image.alt = details.filename;
|
||||||
image.src = result.dataUrl;
|
image.src = result.dataUrl;
|
||||||
target.append(image);
|
target.append(image);
|
||||||
} else if (result.kind === 'text') {
|
} else if (result.kind === 'text') {
|
||||||
const pre = document.createElement('pre');
|
const pre = document.createElement('pre');
|
||||||
pre.className = 'attachment-preview-text';
|
pre.className = 'attachment-preview-text';
|
||||||
pre.textContent = result.text + (result.truncated ? '\n… (preview truncated)' : '');
|
pre.textContent = result.text + (result.truncated ? '\n… (preview truncated)' : '');
|
||||||
target.append(pre);
|
target.append(pre);
|
||||||
} else {
|
} else {
|
||||||
target.textContent = result.reason || 'No preview is available for this file type.';
|
target.textContent = result.reason || 'No preview is available for this file type.';
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
target.textContent = error.message || 'Could not load the preview.';
|
target.textContent = error.message || 'Could not load the preview.';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function downloadAttachment(details) {
|
function downloadAttachment(details) {
|
||||||
if (!details.uid || !window.daybreakMail?.saveAttachment) { toastAttachmentUi('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) toastAttachmentUi('Attachment saved'); })
|
.then(result => { if (result.saved) toastAttachmentUi('Attachment saved'); })
|
||||||
.catch(error => toastAttachmentUi(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.
|
||||||
attachmentMailUi.wrapOpenMessage(baseOpenMessage => function (id) {
|
attachmentMailUi.wrapOpenMessage(baseOpenMessage => function (id) {
|
||||||
baseOpenMessage(id);
|
baseOpenMessage(id);
|
||||||
const message = attachmentMailUi.state.messages.find(item => item.id === id);
|
const message = attachmentMailUi.state.messages.find(item => item.id === id);
|
||||||
if (!message?.uid) return;
|
if (!message?.uid) return;
|
||||||
selectAllAttachmentUi('#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');
|
||||||
button.className = 'preview-attachment icon-button';
|
button.className = 'preview-attachment icon-button';
|
||||||
button.title = 'Preview';
|
button.title = 'Preview';
|
||||||
button.setAttribute('aria-label', `Preview ${download.dataset.filename}`);
|
button.setAttribute('aria-label', `Preview ${download.dataset.filename}`);
|
||||||
button.textContent = '👁';
|
button.textContent = '👁';
|
||||||
button.addEventListener('click', event => {
|
button.addEventListener('click', event => {
|
||||||
event.stopPropagation();
|
event.stopPropagation();
|
||||||
let panel = row.nextElementSibling?.classList.contains('attachment-preview') ? row.nextElementSibling : null;
|
let panel = row.nextElementSibling?.classList.contains('attachment-preview') ? row.nextElementSibling : null;
|
||||||
if (panel) { panel.remove(); return; }
|
if (panel) { panel.remove(); return; }
|
||||||
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 || attachmentMailUi.state.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 = [];
|
||||||
for (const folder of attachmentFolders) {
|
for (const folder of attachmentFolders) {
|
||||||
let offset = 0;
|
let offset = 0;
|
||||||
for (let page = 0; page < 5; page += 1) {
|
for (let page = 0; page < 5; page += 1) {
|
||||||
const result = await window.daybreakMail.syncFolder(folder, offset, { hasAttachments: true });
|
const result = await window.daybreakMail.syncFolder(folder, offset, { hasAttachments: true });
|
||||||
for (const message of result.messages || []) {
|
for (const message of result.messages || []) {
|
||||||
for (const file of message.attachments || []) {
|
for (const file of message.attachments || []) {
|
||||||
items.push({
|
items.push({
|
||||||
uid: message.uid, folder, filename: file.filename, size: file.size,
|
uid: message.uid, folder, filename: file.filename, size: file.size,
|
||||||
subject: message.subject, sender: message.sender, date: message.date, timestamp: Number(message.timestamp || 0),
|
subject: message.subject, sender: message.sender, date: message.date, timestamp: Number(message.timestamp || 0),
|
||||||
kind: attachmentKind(file.filename)
|
kind: attachmentKind(file.filename)
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
offset += (result.messages || []).length;
|
offset += (result.messages || []).length;
|
||||||
if (!result.messages?.length || offset >= (result.total || 0)) break;
|
if (!result.messages?.length || offset >= (result.total || 0)) break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return items.sort((a, b) => b.timestamp - a.timestamp);
|
return items.sort((a, b) => b.timestamp - a.timestamp);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function openAttachmentsView() {
|
async function openAttachmentsView() {
|
||||||
if (!attachmentMailUi.connectedAccount || !window.daybreakMail) { attachmentMailUi.openMailAccount(); return; }
|
if (!attachmentMailUi.connectedAccount || !window.daybreakMail) { attachmentMailUi.openMailAccount(); return; }
|
||||||
const root = selectAttachmentUi('#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 = selectAttachmentUi('#attachment-list');
|
const list = selectAttachmentUi('#attachment-list');
|
||||||
const render = () => {
|
const render = () => {
|
||||||
const text = selectAttachmentUi('#attachment-search').value.trim().toLowerCase();
|
const text = selectAttachmentUi('#attachment-search').value.trim().toLowerCase();
|
||||||
const type = selectAttachmentUi('#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();
|
||||||
if (!shown.length) { list.textContent = attachmentItems.length ? 'No attachments match.' : 'No attachments found.'; return; }
|
if (!shown.length) { list.textContent = attachmentItems.length ? 'No attachments match.' : 'No attachments found.'; return; }
|
||||||
shown.forEach(item => {
|
shown.forEach(item => {
|
||||||
const row = document.createElement('div');
|
const row = document.createElement('div');
|
||||||
row.className = 'attachment-row';
|
row.className = 'attachment-row';
|
||||||
const info = document.createElement('div');
|
const info = document.createElement('div');
|
||||||
info.className = 'attachment-row-info';
|
info.className = 'attachment-row-info';
|
||||||
const name = document.createElement('strong');
|
const name = document.createElement('strong');
|
||||||
name.textContent = item.filename;
|
name.textContent = item.filename;
|
||||||
const meta = document.createElement('small');
|
const meta = document.createElement('small');
|
||||||
meta.textContent = [attachmentSize(item.size), item.sender, item.subject, item.folder, item.date].filter(Boolean).join(' · ');
|
meta.textContent = [attachmentSize(item.size), item.sender, item.subject, item.folder, item.date].filter(Boolean).join(' · ');
|
||||||
info.append(name, meta);
|
info.append(name, meta);
|
||||||
const preview = document.createElement('button');
|
const preview = document.createElement('button');
|
||||||
preview.className = 'discard';
|
preview.className = 'discard';
|
||||||
preview.textContent = 'Preview';
|
preview.textContent = 'Preview';
|
||||||
const save = document.createElement('button');
|
const save = document.createElement('button');
|
||||||
save.className = 'discard';
|
save.className = 'discard';
|
||||||
save.textContent = 'Download';
|
save.textContent = 'Download';
|
||||||
const panel = document.createElement('div');
|
const panel = document.createElement('div');
|
||||||
panel.className = 'attachment-preview';
|
panel.className = 'attachment-preview';
|
||||||
panel.hidden = true;
|
panel.hidden = true;
|
||||||
const details = { uid: item.uid, folder: item.folder, filename: item.filename };
|
const details = { uid: item.uid, folder: item.folder, filename: item.filename };
|
||||||
preview.onclick = () => {
|
preview.onclick = () => {
|
||||||
panel.hidden = !panel.hidden;
|
panel.hidden = !panel.hidden;
|
||||||
if (!panel.hidden && !panel.childElementCount && !panel.textContent) void previewAttachment(panel, details);
|
if (!panel.hidden && !panel.childElementCount && !panel.textContent) void previewAttachment(panel, details);
|
||||||
};
|
};
|
||||||
save.onclick = () => downloadAttachment(details);
|
save.onclick = () => downloadAttachment(details);
|
||||||
row.append(info, preview, save, panel);
|
row.append(info, preview, save, panel);
|
||||||
list.append(row);
|
list.append(row);
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
selectAttachmentUi('#attachment-search').oninput = render;
|
selectAttachmentUi('#attachment-search').oninput = render;
|
||||||
selectAttachmentUi('#attachment-type').onchange = render;
|
selectAttachmentUi('#attachment-type').onchange = render;
|
||||||
try {
|
try {
|
||||||
attachmentItems = await collectAttachments();
|
attachmentItems = await collectAttachments();
|
||||||
if (selectAttachmentUi('#attachment-list')) render();
|
if (selectAttachmentUi('#attachment-list')) render();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (selectAttachmentUi('#attachment-list')) selectAttachmentUi('#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', () => {
|
||||||
selectAttachmentUi('#attachments-nav')?.addEventListener('click', openAttachmentsView);
|
selectAttachmentUi('#attachments-nav')?.addEventListener('click', openAttachmentsView);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,30 +1,30 @@
|
|||||||
.brand-mark,
|
.brand-mark,
|
||||||
body.wasteland .brand-mark,
|
body.wasteland .brand-mark,
|
||||||
body.ep-wasteland .brand-mark,
|
body.ep-wasteland .brand-mark,
|
||||||
body.ep-daylight .brand-mark {
|
body.ep-daylight .brand-mark {
|
||||||
background: transparent !important;
|
background: transparent !important;
|
||||||
box-shadow: none !important;
|
box-shadow: none !important;
|
||||||
border-radius: 0;
|
border-radius: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.brand-mark img {
|
.brand-mark img {
|
||||||
display: block;
|
display: block;
|
||||||
width: 35px;
|
width: 35px;
|
||||||
height: 35px;
|
height: 35px;
|
||||||
object-fit: contain;
|
object-fit: contain;
|
||||||
}
|
}
|
||||||
|
|
||||||
.settings-select {
|
.settings-select {
|
||||||
flex: 1;
|
flex: 1;
|
||||||
border: 0;
|
border: 0;
|
||||||
padding: 5px 0;
|
padding: 5px 0;
|
||||||
background: transparent;
|
background: transparent;
|
||||||
color: var(--text);
|
color: var(--text);
|
||||||
font: inherit;
|
font: inherit;
|
||||||
text-align: right;
|
text-align: right;
|
||||||
}
|
}
|
||||||
|
|
||||||
body.ep-wasteland .settings-select,
|
body.ep-wasteland .settings-select,
|
||||||
body.ep-daylight .settings-select {
|
body.ep-daylight .settings-select {
|
||||||
color-scheme: inherit;
|
color-scheme: inherit;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
{
|
{
|
||||||
"appId": "studio.daybreak.mail",
|
"appId": "studio.daybreak.mail",
|
||||||
"appName": "ep-mail",
|
"appName": "ep-mail",
|
||||||
"webDir": "www",
|
"webDir": "www",
|
||||||
"server": {
|
"server": {
|
||||||
"androidScheme": "https"
|
"androidScheme": "https"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,42 +3,42 @@ const davProductivityUi = window.epMailFeatures.productivity;
|
|||||||
const selectDavUi = davProductivityUi.select;
|
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'?davProductivityUi.events.filter(item=>!item._dav):davProductivityUi.contacts.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){davProductivityUi.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}`)}}
|
||||||
davProductivityUi.events=[...localOnly,...result.items];
|
davProductivityUi.events=[...localOnly,...result.items];
|
||||||
davProductivityUi.productWrite(davProductivityUi.productKeys.events,davProductivityUi.events);davProductivityUi.renderCalendar();davProductivityUi.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){davProductivityUi.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}`)}}
|
||||||
davProductivityUi.contacts=[...localOnly,...result.items];
|
davProductivityUi.contacts=[...localOnly,...result.items];
|
||||||
davProductivityUi.productWrite(davProductivityUi.productKeys.contacts,davProductivityUi.contacts);davProductivityUi.renderContacts();davProductivityUi.toast(`Synced ${result.items.length} contacts`);
|
davProductivityUi.productWrite(davProductivityUi.productKeys.contacts,davProductivityUi.contacts);davProductivityUi.renderContacts();davProductivityUi.toast(`Synced ${result.items.length} contacts`);
|
||||||
}
|
}
|
||||||
}catch(error){davProductivityUi.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=selectDavUi('#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>${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('');
|
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){davProductivityUi.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'){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)} }
|
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){davProductivityUi.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=selectDavUi('#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();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-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({
|
window.epMailFeatures.dav = Object.freeze({
|
||||||
|
|||||||
@@ -41,43 +41,43 @@ function registerMailIpcHandlers(dependencies) {
|
|||||||
pgpFailure
|
pgpFailure
|
||||||
} = dependencies;
|
} = dependencies;
|
||||||
|
|
||||||
registerIpcHandler('mail:get-account', async () => {
|
registerIpcHandler('mail:get-account', async () => {
|
||||||
const account = await readAccount();
|
const account = await readAccount();
|
||||||
return account ? publicAccount(account) : null;
|
return account ? publicAccount(account) : null;
|
||||||
});
|
});
|
||||||
|
|
||||||
registerIpcHandler('mail:list-accounts', async () => {
|
registerIpcHandler('mail:list-accounts', async () => {
|
||||||
const store = (await readAccountStore()) || { accounts: [], activeId: null };
|
const store = (await readAccountStore()) || { accounts: [], activeId: null };
|
||||||
return { accounts: store.accounts.map(publicAccount), activeId: store.activeId };
|
return { accounts: store.accounts.map(publicAccount), activeId: store.activeId };
|
||||||
});
|
});
|
||||||
|
|
||||||
registerIpcHandler('mail:list-oauth-providers', async () => listOAuthProviders());
|
registerIpcHandler('mail:list-oauth-providers', async () => listOAuthProviders());
|
||||||
|
|
||||||
registerIpcHandler('mail:select-account', async (_event, accountId) => {
|
registerIpcHandler('mail:select-account', async (_event, accountId) => {
|
||||||
const account = await updateAccountStore(store => {
|
const account = await updateAccountStore(store => {
|
||||||
const selected = store.accounts.find(item => item.id === accountId);
|
const selected = store.accounts.find(item => item.id === accountId);
|
||||||
if (!selected) throw new Error('That mail account is no longer available.');
|
if (!selected) throw new Error('That mail account is no longer available.');
|
||||||
store.activeId = selected.id;
|
store.activeId = selected.id;
|
||||||
return selected;
|
return selected;
|
||||||
});
|
});
|
||||||
requestBackgroundSync();
|
requestBackgroundSync();
|
||||||
return publicAccount(account);
|
return publicAccount(account);
|
||||||
});
|
});
|
||||||
|
|
||||||
registerIpcHandler('mail:remove-account', async (_event, accountId) => {
|
registerIpcHandler('mail:remove-account', async (_event, accountId) => {
|
||||||
const result = await updateAccountStore(store => {
|
const result = await updateAccountStore(store => {
|
||||||
store.accounts = store.accounts.filter(account => account.id !== accountId);
|
store.accounts = store.accounts.filter(account => account.id !== accountId);
|
||||||
if (store.activeId === accountId) store.activeId = store.accounts[0]?.id || null;
|
if (store.activeId === accountId) store.activeId = store.accounts[0]?.id || null;
|
||||||
return { accounts: store.accounts.map(publicAccount), activeId: store.activeId };
|
return { accounts: store.accounts.map(publicAccount), activeId: store.activeId };
|
||||||
});
|
});
|
||||||
requestBackgroundSync(accountId);
|
requestBackgroundSync(accountId);
|
||||||
requestBackgroundSync();
|
requestBackgroundSync();
|
||||||
return result;
|
return result;
|
||||||
});
|
});
|
||||||
|
|
||||||
registerIpcHandler('mail:update-account', async (_event, accountId, input) => {
|
registerIpcHandler('mail:update-account', async (_event, accountId, input) => {
|
||||||
const existing = await readAccount(accountId);
|
const existing = await readAccount(accountId);
|
||||||
if (!existing) throw new Error('That mail account is no longer available.');
|
if (!existing) throw new Error('That mail account is no longer available.');
|
||||||
let account = normalizeAccount({
|
let account = normalizeAccount({
|
||||||
...existing,
|
...existing,
|
||||||
...input,
|
...input,
|
||||||
@@ -95,190 +95,190 @@ registerIpcHandler('mail:update-account', async (_event, accountId, input) => {
|
|||||||
account.id = existing.id;
|
account.id = existing.id;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
const status = await connectMail(account);
|
const status = await connectMail(account);
|
||||||
const savedAccount = await updateAccountStore(store => {
|
const savedAccount = await updateAccountStore(store => {
|
||||||
const current = store.accounts.find(item => item.id === existing.id);
|
const current = store.accounts.find(item => item.id === existing.id);
|
||||||
if (!current) throw new Error('That mail account is no longer available.');
|
if (!current) throw new Error('That mail account is no longer available.');
|
||||||
const endpointChanged = current.email !== account.email || current.imapHost !== account.imapHost;
|
const endpointChanged = current.email !== account.email || current.imapHost !== account.imapHost;
|
||||||
store.accounts = store.accounts.map(item => item.id === existing.id
|
store.accounts = store.accounts.map(item => item.id === existing.id
|
||||||
? {
|
? {
|
||||||
...account,
|
...account,
|
||||||
syncState: endpointChanged ? undefined : current.syncState,
|
syncState: endpointChanged ? undefined : current.syncState,
|
||||||
snoozedMessages: endpointChanged ? [] : (current.snoozedMessages || []),
|
snoozedMessages: endpointChanged ? [] : (current.snoozedMessages || []),
|
||||||
ruleLabels: endpointChanged ? {} : (current.ruleLabels || {})
|
ruleLabels: endpointChanged ? {} : (current.ruleLabels || {})
|
||||||
}
|
}
|
||||||
: item);
|
: item);
|
||||||
return store.accounts.find(item => item.id === existing.id);
|
return store.accounts.find(item => item.id === existing.id);
|
||||||
});
|
});
|
||||||
requestBackgroundSync(existing.id);
|
requestBackgroundSync(existing.id);
|
||||||
return { ...publicAccount(savedAccount), ...status };
|
return { ...publicAccount(savedAccount), ...status };
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
throw new Error(`Could not update the mailbox: ${error.message}`);
|
throw new Error(`Could not update the mailbox: ${error.message}`);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
registerIpcHandler('mail:connect', async (_event, input) => {
|
registerIpcHandler('mail:connect', async (_event, input) => {
|
||||||
let account = normalizeAccount(input);
|
let account = normalizeAccount(input);
|
||||||
try {
|
try {
|
||||||
if (account.authMethod === 'oauth2') account = await authorizeOAuthAccount(account);
|
if (account.authMethod === 'oauth2') account = await authorizeOAuthAccount(account);
|
||||||
const status = await connectMail(account);
|
const status = await connectMail(account);
|
||||||
const saved = await saveAccount(account);
|
const saved = await saveAccount(account);
|
||||||
requestBackgroundSync(saved.id);
|
requestBackgroundSync(saved.id);
|
||||||
return { ok: true, ...publicAccount(saved), ...status };
|
return { ok: true, ...publicAccount(saved), ...status };
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
throw new Error(`Could not connect to the mailbox: ${error.message}`);
|
throw new Error(`Could not connect to the mailbox: ${error.message}`);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
registerIpcHandler('mail:sync-folder', async (_event, requestedFolder, offset = 0, filters = {}) => {
|
registerIpcHandler('mail:sync-folder', async (_event, requestedFolder, offset = 0, filters = {}) => {
|
||||||
const account = await readAccount();
|
const account = await readAccount();
|
||||||
if (!account) throw new Error('Add a mail account before syncing.');
|
if (!account) throw new Error('Add a mail account before syncing.');
|
||||||
const allowedFolders = new Set(['Inbox', 'Sent', 'Archive', 'Trash', 'Starred', 'Snoozed']);
|
const allowedFolders = new Set(['Inbox', 'Sent', 'Archive', 'Trash', 'Starred', 'Snoozed']);
|
||||||
const selectedFolder = allowedFolders.has(filters.folder) ? filters.folder : requestedFolder;
|
const selectedFolder = allowedFolders.has(filters.folder) ? filters.folder : requestedFolder;
|
||||||
const folder = allowedFolders.has(selectedFolder) || String(selectedFolder).startsWith(CUSTOM_FOLDER_PREFIX)
|
const folder = allowedFolders.has(selectedFolder) || String(selectedFolder).startsWith(CUSTOM_FOLDER_PREFIX)
|
||||||
? selectedFolder : 'Inbox';
|
? selectedFolder : 'Inbox';
|
||||||
const { folder: _filterFolder, ...criteria } = filters;
|
const { folder: _filterFolder, ...criteria } = filters;
|
||||||
try {
|
try {
|
||||||
await flushMailOutbox(account);
|
await flushMailOutbox(account);
|
||||||
return await fetchMailbox(account, folder, offset, 20, criteria);
|
return await fetchMailbox(account, folder, offset, 20, criteria);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (!isConnectivityFailure(error)) throw error;
|
if (!isConnectivityFailure(error)) throw error;
|
||||||
const cached = cachedMailbox(account, folder, offset, 20, criteria);
|
const cached = cachedMailbox(account, folder, offset, 20, criteria);
|
||||||
if (!cached.total) throw error;
|
if (!cached.total) throw error;
|
||||||
return cached;
|
return cached;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
registerIpcHandler('mail:list-folders', async () => {
|
registerIpcHandler('mail:list-folders', async () => {
|
||||||
const account = await readAccount();
|
const account = await readAccount();
|
||||||
if (!account) throw new Error('Add a mail account before listing folders.');
|
if (!account) throw new Error('Add a mail account before listing folders.');
|
||||||
const client = await imapClient(account);
|
const client = await imapClient(account);
|
||||||
try {
|
try {
|
||||||
await client.connect();
|
await client.connect();
|
||||||
return { folders: await listCustomFolders(client) };
|
return { folders: await listCustomFolders(client) };
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (isConnectivityFailure(error)) return { folders: [], offline: true };
|
if (isConnectivityFailure(error)) return { folders: [], offline: true };
|
||||||
throw error;
|
throw error;
|
||||||
} finally {
|
} finally {
|
||||||
if (client.usable) await client.logout().catch(() => {});
|
if (client.usable) await client.logout().catch(() => {});
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
registerIpcHandler('mail:create-folder', async (_event, input) => {
|
registerIpcHandler('mail:create-folder', async (_event, input) => {
|
||||||
const account = await readAccount();
|
const account = await readAccount();
|
||||||
if (!account) throw new Error('Add a mail account before creating folders.');
|
if (!account) throw new Error('Add a mail account before creating folders.');
|
||||||
const name = validFolderName(input?.name);
|
const name = validFolderName(input?.name);
|
||||||
const client = await imapClient(account);
|
const client = await imapClient(account);
|
||||||
try {
|
try {
|
||||||
await client.connect();
|
await client.connect();
|
||||||
const existing = await client.list();
|
const existing = await client.list();
|
||||||
if (existing.some(mailbox => mailbox.path.toLowerCase() === name.toLowerCase())) {
|
if (existing.some(mailbox => mailbox.path.toLowerCase() === name.toLowerCase())) {
|
||||||
throw new Error('A folder with that name already exists.');
|
throw new Error('A folder with that name already exists.');
|
||||||
}
|
}
|
||||||
const created = await client.mailboxCreate(name);
|
const created = await client.mailboxCreate(name);
|
||||||
await client.mailboxSubscribe(created.path).catch(() => {});
|
await client.mailboxSubscribe(created.path).catch(() => {});
|
||||||
return { ok: true, folder: { name, path: created.path, id: CUSTOM_FOLDER_PREFIX + created.path }, folders: await listCustomFolders(client) };
|
return { ok: true, folder: { name, path: created.path, id: CUSTOM_FOLDER_PREFIX + created.path }, folders: await listCustomFolders(client) };
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (error.message === 'A folder with that name already exists.') throw error;
|
if (error.message === 'A folder with that name already exists.') throw error;
|
||||||
throw new Error(`Could not create the folder: ${error.message}`);
|
throw new Error(`Could not create the folder: ${error.message}`);
|
||||||
} finally {
|
} finally {
|
||||||
if (client.usable) await client.logout().catch(() => {});
|
if (client.usable) await client.logout().catch(() => {});
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
registerIpcHandler('mail:list-drafts', async () => {
|
registerIpcHandler('mail:list-drafts', async () => {
|
||||||
const account = await readAccount();
|
const account = await readAccount();
|
||||||
if (!account) throw new Error('Add a mail account before opening drafts.');
|
if (!account) throw new Error('Add a mail account before opening drafts.');
|
||||||
return { drafts: account.drafts || [], offline: true };
|
return { drafts: account.drafts || [], offline: true };
|
||||||
});
|
});
|
||||||
|
|
||||||
registerIpcHandler('mail:save-draft', async (_event, input) => {
|
registerIpcHandler('mail:save-draft', async (_event, input) => {
|
||||||
const account = await readAccount();
|
const account = await readAccount();
|
||||||
if (!account) throw new Error('Add a mail account before saving drafts.');
|
if (!account) throw new Error('Add a mail account before saving drafts.');
|
||||||
const draft = {
|
const draft = {
|
||||||
id: String(input?.id || randomUUID()),
|
id: String(input?.id || randomUUID()),
|
||||||
to: String(input?.to || '').slice(0, 4000),
|
to: String(input?.to || '').slice(0, 4000),
|
||||||
cc: String(input?.cc || '').slice(0, 4000),
|
cc: String(input?.cc || '').slice(0, 4000),
|
||||||
subject: String(input?.subject || '').slice(0, 998),
|
subject: String(input?.subject || '').slice(0, 998),
|
||||||
text: String(input?.text || '').slice(0, 500000),
|
text: String(input?.text || '').slice(0, 500000),
|
||||||
attachments: serializeOutgoingAttachments(normalizeOutgoingAttachments(input?.attachments)),
|
attachments: serializeOutgoingAttachments(normalizeOutgoingAttachments(input?.attachments)),
|
||||||
updatedAt: Date.now()
|
updatedAt: Date.now()
|
||||||
};
|
};
|
||||||
await updateAccountStore(store => {
|
await updateAccountStore(store => {
|
||||||
const saved = store.accounts.find(item => item.id === account.id);
|
const saved = store.accounts.find(item => item.id === account.id);
|
||||||
if (!saved) throw new Error('That mail account is no longer available.');
|
if (!saved) throw new Error('That mail account is no longer available.');
|
||||||
const drafts = saved.drafts || [];
|
const drafts = saved.drafts || [];
|
||||||
saved.drafts = [draft, ...drafts.filter(item => item.id !== draft.id)].slice(0, 500);
|
saved.drafts = [draft, ...drafts.filter(item => item.id !== draft.id)].slice(0, 500);
|
||||||
});
|
});
|
||||||
return draft;
|
return draft;
|
||||||
});
|
});
|
||||||
|
|
||||||
registerIpcHandler('mail:delete-draft', async (_event, id) => {
|
registerIpcHandler('mail:delete-draft', async (_event, id) => {
|
||||||
const account = await readAccount();
|
const account = await readAccount();
|
||||||
if (!account) throw new Error('Add a mail account before deleting drafts.');
|
if (!account) throw new Error('Add a mail account before deleting drafts.');
|
||||||
await updateAccountStore(store => {
|
await updateAccountStore(store => {
|
||||||
const saved = store.accounts.find(item => item.id === account.id);
|
const saved = store.accounts.find(item => item.id === account.id);
|
||||||
if (saved) saved.drafts = (saved.drafts || []).filter(draft => draft.id !== id);
|
if (saved) saved.drafts = (saved.drafts || []).filter(draft => draft.id !== id);
|
||||||
});
|
});
|
||||||
return { ok: true };
|
return { ok: true };
|
||||||
});
|
});
|
||||||
|
|
||||||
registerIpcHandler('mail:set-snooze', async (_event, input) => {
|
registerIpcHandler('mail:set-snooze', async (_event, input) => {
|
||||||
const account = await readAccount();
|
const account = await readAccount();
|
||||||
if (!account) throw new Error('Add a mail account before setting a reminder.');
|
if (!account) throw new Error('Add a mail account before setting a reminder.');
|
||||||
const uid = Number(input?.uid);
|
const uid = Number(input?.uid);
|
||||||
const folder = String(input?.sourceFolder || input?.folder || 'Inbox');
|
const folder = String(input?.sourceFolder || input?.folder || 'Inbox');
|
||||||
if (!Number.isInteger(uid) || uid < 1) throw new Error('That message could not be identified.');
|
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.');
|
if (!['Inbox', 'Sent', 'Archive', 'Trash'].includes(folder)) throw new Error('That mailbox cannot be snoozed.');
|
||||||
const dueAt = input?.dueAt == null ? null : Number(input.dueAt);
|
const dueAt = input?.dueAt == null ? null : Number(input.dueAt);
|
||||||
if (dueAt != null && (!Number.isFinite(dueAt) || dueAt <= Date.now())) {
|
if (dueAt != null && (!Number.isFinite(dueAt) || dueAt <= Date.now())) {
|
||||||
throw new Error('Choose a reminder time in the future.');
|
throw new Error('Choose a reminder time in the future.');
|
||||||
}
|
}
|
||||||
await updateAccountStore(store => {
|
await updateAccountStore(store => {
|
||||||
const saved = store.accounts.find(item => item.id === account.id);
|
const saved = store.accounts.find(item => item.id === account.id);
|
||||||
if (!saved) throw new Error('That mail account is no longer available.');
|
if (!saved) throw new Error('That mail account is no longer available.');
|
||||||
const snoozes = saved.snoozedMessages || [];
|
const snoozes = saved.snoozedMessages || [];
|
||||||
const remaining = snoozes.filter(item => !(Number(item.uid) === uid && item.folder === folder));
|
const remaining = snoozes.filter(item => !(Number(item.uid) === uid && item.folder === folder));
|
||||||
if (dueAt != null) {
|
if (dueAt != null) {
|
||||||
remaining.push({
|
remaining.push({
|
||||||
uid,
|
uid,
|
||||||
folder,
|
folder,
|
||||||
dueAt,
|
dueAt,
|
||||||
subject: String(input.subject || '').slice(0, 200)
|
subject: String(input.subject || '').slice(0, 200)
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
saved.snoozedMessages = remaining;
|
saved.snoozedMessages = remaining;
|
||||||
});
|
});
|
||||||
sendMailSyncUpdate({
|
sendMailSyncUpdate({
|
||||||
accountId: account.id,
|
accountId: account.id,
|
||||||
foldersChanged: ['Snoozed', folder]
|
foldersChanged: ['Snoozed', folder]
|
||||||
});
|
});
|
||||||
return { ok: true, snoozed: dueAt != null };
|
return { ok: true, snoozed: dueAt != null };
|
||||||
});
|
});
|
||||||
|
|
||||||
registerIpcHandler('mail:update-message', async (_event, input) => {
|
registerIpcHandler('mail:update-message', async (_event, input) => {
|
||||||
const account = await readAccount();
|
const account = await readAccount();
|
||||||
if (!account) throw new Error('Add a mail account before changing messages.');
|
if (!account) throw new Error('Add a mail account before changing messages.');
|
||||||
try {
|
try {
|
||||||
return await applyMessageAction(account, input);
|
return await applyMessageAction(account, input);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (!isConnectivityFailure(error)) throw error;
|
if (!isConnectivityFailure(error)) throw error;
|
||||||
return mailOutbox.queueMessageAction(account, input);
|
return mailOutbox.queueMessageAction(account, input);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// Encrypted messages keep their attachments inside the encrypted payload.
|
// Encrypted messages keep their attachments inside the encrypted payload.
|
||||||
async function parseForAttachments(source) {
|
async function parseForAttachments(source) {
|
||||||
const { simpleParser } = await getMailparser();
|
const { simpleParser } = await getMailparser();
|
||||||
const parsed = await simpleParser(source);
|
const parsed = await simpleParser(source);
|
||||||
const kind = pgpMail.detect(parsed);
|
const kind = pgpMail.detect(parsed);
|
||||||
if (kind !== 'encrypted-mime' && kind !== 'encrypted-inline') return parsed;
|
if (kind !== 'encrypted-mime' && kind !== 'encrypted-inline') return parsed;
|
||||||
try {
|
try {
|
||||||
return (await pgpMail.decrypt(parsed)).parsed;
|
return (await pgpMail.decrypt(parsed)).parsed;
|
||||||
} catch (error) {
|
} 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);
|
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;
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const attachmentService = createAttachmentService({ imapClient, folderPath, parseForAttachments });
|
const attachmentService = createAttachmentService({ imapClient, folderPath, parseForAttachments });
|
||||||
@@ -295,34 +295,34 @@ registerIpcHandler('mail:preview-attachment', async (_event, input) => {
|
|||||||
if (!account) throw new Error('Add a mail account before previewing attachments.');
|
if (!account) throw new Error('Add a mail account before previewing attachments.');
|
||||||
return attachmentService.previewAttachment(account, input);
|
return attachmentService.previewAttachment(account, input);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
|
registerIpcHandler('mail:open-external', async (event, rawUrl) => {
|
||||||
registerIpcHandler('mail:open-external', async (event, rawUrl) => {
|
let target;
|
||||||
let target;
|
try {
|
||||||
try {
|
target = new URL(String(rawUrl || ''));
|
||||||
target = new URL(String(rawUrl || ''));
|
} catch {
|
||||||
} catch {
|
throw new Error('This link is not a valid web address.');
|
||||||
throw new Error('This link is not a valid web address.');
|
}
|
||||||
}
|
if (!['http:', 'https:'].includes(target.protocol) || target.username || target.password) {
|
||||||
if (!['http:', 'https:'].includes(target.protocol) || target.username || target.password) {
|
throw new Error('Only standard web links can be opened from mail.');
|
||||||
throw new Error('Only standard web links can be opened from mail.');
|
}
|
||||||
}
|
const parent = BrowserWindow.fromWebContents(event.sender);
|
||||||
const parent = BrowserWindow.fromWebContents(event.sender);
|
const confirmation = await dialog.showMessageBox(parent, {
|
||||||
const confirmation = await dialog.showMessageBox(parent, {
|
type: 'warning',
|
||||||
type: 'warning',
|
title: 'Open external link?',
|
||||||
title: 'Open external link?',
|
message: 'Email links can lead to fake sign-in pages or harmful content.',
|
||||||
message: 'Email links can lead to fake sign-in pages or harmful content.',
|
detail: `Check the full address before continuing:\n${target.href}`,
|
||||||
detail: `Check the full address before continuing:\n${target.href}`,
|
buttons: ['Cancel', 'Open link'],
|
||||||
buttons: ['Cancel', 'Open link'],
|
defaultId: 0,
|
||||||
defaultId: 0,
|
cancelId: 0,
|
||||||
cancelId: 0,
|
noLink: true
|
||||||
noLink: true
|
});
|
||||||
});
|
if (confirmation.response !== 1) return { opened: false };
|
||||||
if (confirmation.response !== 1) return { opened: false };
|
await shell.openExternal(target.href);
|
||||||
await shell.openExternal(target.href);
|
return { opened: true };
|
||||||
return { opened: true };
|
});
|
||||||
});
|
|
||||||
|
|
||||||
registerIpcHandler('mail:sync-inbox', async () => {
|
registerIpcHandler('mail:sync-inbox', async () => {
|
||||||
const account = await readAccount();
|
const account = await readAccount();
|
||||||
if (!account) throw new Error('Add a mail account before syncing.');
|
if (!account) throw new Error('Add a mail account before syncing.');
|
||||||
@@ -343,83 +343,83 @@ registerIpcHandler('mail:send', async (event, message) => {
|
|||||||
messageId: message.messageId || `<${randomUUID()}@ep-mail.local>`,
|
messageId: message.messageId || `<${randomUUID()}@ep-mail.local>`,
|
||||||
attachments: message.attachments
|
attachments: message.attachments
|
||||||
};
|
};
|
||||||
const attachments = normalizeOutgoingAttachments(message?.attachments);
|
const attachments = normalizeOutgoingAttachments(message?.attachments);
|
||||||
queuedMessage.attachments = serializeOutgoingAttachments(attachments);
|
queuedMessage.attachments = serializeOutgoingAttachments(attachments);
|
||||||
delete queuedMessage.pgp;
|
delete queuedMessage.pgp;
|
||||||
if (!pgpOptions?.encrypt) {
|
if (!pgpOptions?.encrypt) {
|
||||||
const recipients = [queuedMessage.to, queuedMessage.cc].filter(Boolean);
|
const recipients = [queuedMessage.to, queuedMessage.cc].filter(Boolean);
|
||||||
const status = await pgpMail.recipientStatus(recipients, { sign: Boolean(pgpOptions?.sign), from: account.email });
|
const status = await pgpMail.recipientStatus(recipients, { sign: Boolean(pgpOptions?.sign), from: account.email });
|
||||||
if (status.recipients.length && !status.missing.length) {
|
if (status.recipients.length && !status.missing.length) {
|
||||||
const { response } = await dialog.showMessageBox(BrowserWindow.fromWebContents(event.sender), {
|
const { response } = await dialog.showMessageBox(BrowserWindow.fromWebContents(event.sender), {
|
||||||
type: 'warning',
|
type: 'warning',
|
||||||
buttons: ['Cancel', 'Send anyway'],
|
buttons: ['Cancel', 'Send anyway'],
|
||||||
defaultId: 0,
|
defaultId: 0,
|
||||||
cancelId: 0,
|
cancelId: 0,
|
||||||
title: 'Send without encryption?',
|
title: 'Send without encryption?',
|
||||||
message: 'Public keys are available for all recipients.',
|
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.',
|
detail: 'This message is about to be sent without encryption. Continue only if you explicitly want to send it in plaintext.',
|
||||||
noLink: true
|
noLink: true
|
||||||
});
|
});
|
||||||
if (response !== 1) throw new Error('Plaintext send cancelled.');
|
if (response !== 1) throw new Error('Plaintext send cancelled.');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (pgpOptions) {
|
if (pgpOptions) {
|
||||||
// Encrypt before sending or queueing so plaintext and passphrases are never stored in the outbox.
|
// Encrypt before sending or queueing so plaintext and passphrases are never stored in the outbox.
|
||||||
const signature = String(account.signature || '').slice(0, 5000);
|
const signature = String(account.signature || '').slice(0, 5000);
|
||||||
const body = String(queuedMessage.text || '').slice(0, 500000);
|
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;
|
const fromName = String(account.displayName || queuedMessage.displayName || account.email).replace(/[\r\n]+/g, ' ').trim().slice(0, 80) || account.email;
|
||||||
try {
|
try {
|
||||||
const built = await pgpMail.build({
|
const built = await pgpMail.build({
|
||||||
from: { name: fromName, address: account.email },
|
from: { name: fromName, address: account.email },
|
||||||
to: queuedMessage.to,
|
to: queuedMessage.to,
|
||||||
cc: queuedMessage.cc,
|
cc: queuedMessage.cc,
|
||||||
subject: String(queuedMessage.subject || '(no subject)').slice(0, 998),
|
subject: String(queuedMessage.subject || '(no subject)').slice(0, 998),
|
||||||
text: signature ? `${body}${body.trim() ? '\n\n' : ''}${signature}`.slice(0, 505000) : body,
|
text: signature ? `${body}${body.trim() ? '\n\n' : ''}${signature}`.slice(0, 505000) : body,
|
||||||
messageId: queuedMessage.messageId,
|
messageId: queuedMessage.messageId,
|
||||||
encrypt: Boolean(pgpOptions.encrypt),
|
encrypt: Boolean(pgpOptions.encrypt),
|
||||||
sign: Boolean(pgpOptions.sign),
|
sign: Boolean(pgpOptions.sign),
|
||||||
passphrase: typeof pgpOptions.passphrase === 'string' && pgpOptions.passphrase ? pgpOptions.passphrase : null,
|
passphrase: typeof pgpOptions.passphrase === 'string' && pgpOptions.passphrase ? pgpOptions.passphrase : null,
|
||||||
attachments: attachments.map(({ filename, contentType, content }) => ({ filename, contentType, content }))
|
attachments: attachments.map(({ filename, contentType, content }) => ({ filename, contentType, content }))
|
||||||
});
|
});
|
||||||
queuedMessage.rawBase64 = built.raw.toString('base64');
|
queuedMessage.rawBase64 = built.raw.toString('base64');
|
||||||
queuedMessage.envelope = built.envelope;
|
queuedMessage.envelope = built.envelope;
|
||||||
queuedMessage.text = '';
|
queuedMessage.text = '';
|
||||||
queuedMessage.attachments = [];
|
queuedMessage.attachments = [];
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (error instanceof PgpError) return pgpFailure(error);
|
if (error instanceof PgpError) return pgpFailure(error);
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
return await sendMailNow(account, queuedMessage);
|
return await sendMailNow(account, queuedMessage);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (!isConnectivityFailure(error)) throw error;
|
if (!isConnectivityFailure(error)) throw error;
|
||||||
await updateAccountStore(store => {
|
await updateAccountStore(store => {
|
||||||
const saved = store.accounts.find(item => item.id === account.id);
|
const saved = store.accounts.find(item => item.id === account.id);
|
||||||
if (!saved) throw new Error('That mail account is no longer available.');
|
if (!saved) throw new Error('That mail account is no longer available.');
|
||||||
saved.mailOutbox = saved.mailOutbox || [];
|
saved.mailOutbox = saved.mailOutbox || [];
|
||||||
saved.mailOutbox.push({ id: randomUUID(), type: 'send', data: queuedMessage, createdAt: Date.now() });
|
saved.mailOutbox.push({ id: randomUUID(), type: 'send', data: queuedMessage, createdAt: Date.now() });
|
||||||
});
|
});
|
||||||
return { ok: true, queued: true };
|
return { ok: true, queued: true };
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
registerIpcHandler('mail:disconnect', async (_event, accountId) => {
|
registerIpcHandler('mail:disconnect', async (_event, accountId) => {
|
||||||
const store = await readAccountStore();
|
const store = await readAccountStore();
|
||||||
if (!store) return { accounts: [], activeId: null };
|
if (!store) return { accounts: [], activeId: null };
|
||||||
if (accountId) {
|
if (accountId) {
|
||||||
store.accounts = store.accounts.filter(account => account.id !== accountId);
|
store.accounts = store.accounts.filter(account => account.id !== accountId);
|
||||||
} else {
|
} else {
|
||||||
store.accounts = [];
|
store.accounts = [];
|
||||||
}
|
}
|
||||||
if (!store.accounts.length) await fs.rm(credentialsPath(), { force: true });
|
if (!store.accounts.length) await fs.rm(credentialsPath(), { force: true });
|
||||||
else {
|
else {
|
||||||
if (!store.accounts.some(account => account.id === store.activeId)) store.activeId = store.accounts[0].id;
|
if (!store.accounts.some(account => account.id === store.activeId)) store.activeId = store.accounts[0].id;
|
||||||
await saveAccountStore(store);
|
await saveAccountStore(store);
|
||||||
}
|
}
|
||||||
return { accounts: store.accounts.map(publicAccount), activeId: store.activeId };
|
return { accounts: store.accounts.map(publicAccount), activeId: store.activeId };
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,30 +1,30 @@
|
|||||||
const path = require('node:path');
|
const path = require('node:path');
|
||||||
|
|
||||||
function normalizeOutgoingAttachments(value) {
|
function normalizeOutgoingAttachments(value) {
|
||||||
if (value === undefined) return [];
|
if (value === undefined) return [];
|
||||||
if (!Array.isArray(value)) throw new Error('The attachment list is invalid.');
|
if (!Array.isArray(value)) throw new Error('The attachment list is invalid.');
|
||||||
return value.map(file => {
|
return value.map(file => {
|
||||||
if (!file || typeof file !== 'object' || typeof file.contentBase64 !== 'string') {
|
if (!file || typeof file !== 'object' || typeof file.contentBase64 !== 'string') {
|
||||||
throw new Error('An attachment could not be read.');
|
throw new Error('An attachment could not be read.');
|
||||||
}
|
}
|
||||||
const filename = path.basename(String(file.filename || 'attachment').replace(/\\/g, '/'))
|
const filename = path.basename(String(file.filename || 'attachment').replace(/\\/g, '/'))
|
||||||
.replace(/[\r\n\0]/g, '')
|
.replace(/[\r\n\0]/g, '')
|
||||||
.slice(0, 255) || 'attachment';
|
.slice(0, 255) || 'attachment';
|
||||||
const contentType = String(file.contentType || 'application/octet-stream').trim().toLowerCase();
|
const contentType = String(file.contentType || 'application/octet-stream').trim().toLowerCase();
|
||||||
if (!/^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/.test(contentType)) {
|
if (!/^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/.test(contentType)) {
|
||||||
throw new Error(`The content type for ${filename} is invalid.`);
|
throw new Error(`The content type for ${filename} is invalid.`);
|
||||||
}
|
}
|
||||||
const encoded = file.contentBase64;
|
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)) {
|
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.`);
|
throw new Error(`The contents of ${filename} are invalid.`);
|
||||||
}
|
}
|
||||||
const content = Buffer.from(encoded, 'base64');
|
const content = Buffer.from(encoded, 'base64');
|
||||||
return { filename, contentType, contentBase64: encoded, size: content.length, content };
|
return { filename, contentType, contentBase64: encoded, size: content.length, content };
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function serializeOutgoingAttachments(attachments) {
|
function serializeOutgoingAttachments(attachments) {
|
||||||
return attachments.map(({ content, ...file }) => file);
|
return attachments.map(({ content, ...file }) => file);
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = { normalizeOutgoingAttachments, serializeOutgoingAttachments };
|
module.exports = { normalizeOutgoingAttachments, serializeOutgoingAttachments };
|
||||||
|
|||||||
@@ -10,47 +10,47 @@ function traceStartup(message) {
|
|||||||
traceStartup('main process entered');
|
traceStartup('main process entered');
|
||||||
|
|
||||||
const { app, BrowserWindow, shell, ipcMain, safeStorage, dialog, Notification, powerMonitor, Menu, Tray, nativeImage } = require('electron');
|
const { app, BrowserWindow, shell, ipcMain, safeStorage, dialog, Notification, powerMonitor, Menu, Tray, nativeImage } = require('electron');
|
||||||
const fsSync = require('node:fs');
|
const fsSync = require('node:fs');
|
||||||
const path = require('node:path');
|
const path = require('node:path');
|
||||||
const fs = require('node:fs/promises');
|
const fs = require('node:fs/promises');
|
||||||
const { randomUUID } = require('node:crypto');
|
const { randomUUID } = require('node:crypto');
|
||||||
|
|
||||||
let tsdavPromise = null;
|
let tsdavPromise = null;
|
||||||
function getTsdav() {
|
function getTsdav() {
|
||||||
if (!tsdavPromise) tsdavPromise = import('tsdav');
|
if (!tsdavPromise) tsdavPromise = import('tsdav');
|
||||||
return tsdavPromise;
|
return tsdavPromise;
|
||||||
}
|
}
|
||||||
|
|
||||||
let icalPromise = null;
|
let icalPromise = null;
|
||||||
function getICAL() {
|
function getICAL() {
|
||||||
if (!icalPromise) icalPromise = import('ical.js');
|
if (!icalPromise) icalPromise = import('ical.js');
|
||||||
return icalPromise;
|
return icalPromise;
|
||||||
}
|
}
|
||||||
|
|
||||||
let openpgpPromise = null;
|
let openpgpPromise = null;
|
||||||
function getOpenPGP() {
|
function getOpenPGP() {
|
||||||
if (!openpgpPromise) openpgpPromise = import('openpgp');
|
if (!openpgpPromise) openpgpPromise = import('openpgp');
|
||||||
return openpgpPromise;
|
return openpgpPromise;
|
||||||
}
|
}
|
||||||
|
|
||||||
let imapFlowPromise = null;
|
let imapFlowPromise = null;
|
||||||
function getImapFlow() {
|
function getImapFlow() {
|
||||||
if (!imapFlowPromise) imapFlowPromise = import('imapflow');
|
if (!imapFlowPromise) imapFlowPromise = import('imapflow');
|
||||||
return imapFlowPromise;
|
return imapFlowPromise;
|
||||||
}
|
}
|
||||||
|
|
||||||
let nodemailerPromise = null;
|
let nodemailerPromise = null;
|
||||||
function getNodemailer() {
|
function getNodemailer() {
|
||||||
if (!nodemailerPromise) nodemailerPromise = import('nodemailer');
|
if (!nodemailerPromise) nodemailerPromise = import('nodemailer');
|
||||||
return nodemailerPromise;
|
return nodemailerPromise;
|
||||||
}
|
}
|
||||||
|
|
||||||
let mailparserPromise = null;
|
let mailparserPromise = null;
|
||||||
function getMailparser() {
|
function getMailparser() {
|
||||||
if (!mailparserPromise) mailparserPromise = import('mailparser');
|
if (!mailparserPromise) mailparserPromise = import('mailparser');
|
||||||
return mailparserPromise;
|
return mailparserPromise;
|
||||||
}
|
}
|
||||||
|
|
||||||
const { createKeyServerService, listServers, MAX_CUSTOM_SERVERS, normalizeCustomServer } = require('./pgp-keyservers.cjs');
|
const { createKeyServerService, listServers, MAX_CUSTOM_SERVERS, normalizeCustomServer } = require('./pgp-keyservers.cjs');
|
||||||
const { normalizeOutgoingAttachments, serializeOutgoingAttachments } = require('./mail-attachments.cjs');
|
const { normalizeOutgoingAttachments, serializeOutgoingAttachments } = require('./mail-attachments.cjs');
|
||||||
const {
|
const {
|
||||||
@@ -109,11 +109,11 @@ const pgpJsonStore = createSecureJsonStore({
|
|||||||
assertSecureStorage,
|
assertSecureStorage,
|
||||||
unavailableMessage: 'Secure key storage is unavailable.'
|
unavailableMessage: 'Secure key storage is unavailable.'
|
||||||
});
|
});
|
||||||
const backgroundSyncIntervalMs = 30 * 1000;
|
const backgroundSyncIntervalMs = 30 * 1000;
|
||||||
const backgroundRetryIntervalMs = 2 * 60 * 1000;
|
const backgroundRetryIntervalMs = 2 * 60 * 1000;
|
||||||
const backgroundSyncConcurrency = 2;
|
const backgroundSyncConcurrency = 2;
|
||||||
const backgroundIdleConcurrency = 2;
|
const backgroundIdleConcurrency = 2;
|
||||||
const snoozeCheckIntervalMs = 30 * 1000;
|
const snoozeCheckIntervalMs = 30 * 1000;
|
||||||
const windowsAppUserModelId = 'studio.daybreak.mail';
|
const windowsAppUserModelId = 'studio.daybreak.mail';
|
||||||
const applicationHtmlPath = path.join(__dirname, '..', 'index.html');
|
const applicationHtmlPath = path.join(__dirname, '..', 'index.html');
|
||||||
const ipcMainHandle = ipcMain.handle.bind(ipcMain);
|
const ipcMainHandle = ipcMain.handle.bind(ipcMain);
|
||||||
@@ -122,7 +122,7 @@ const backgroundSyncGenerations = new Map();
|
|||||||
const backgroundSyncFailures = new Map();
|
const backgroundSyncFailures = new Map();
|
||||||
const flagSnapshots = new Map();
|
const flagSnapshots = new Map();
|
||||||
const lastBackgroundSyncAt = new Map();
|
const lastBackgroundSyncAt = new Map();
|
||||||
let windowsAppIcon = null;
|
let windowsAppIcon = null;
|
||||||
let tray = null;
|
let tray = null;
|
||||||
|
|
||||||
function registerIpcHandler(channel, handler) {
|
function registerIpcHandler(channel, handler) {
|
||||||
@@ -140,16 +140,16 @@ function registerIpcHandler(channel, handler) {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function updateAccountStore(update) {
|
function updateAccountStore(update) {
|
||||||
const operation = accountStoreQueue.then(async () => {
|
const operation = accountStoreQueue.then(async () => {
|
||||||
const store = (await readAccountStore()) || { accounts: [], activeId: null };
|
const store = (await readAccountStore()) || { accounts: [], activeId: null };
|
||||||
const result = await update(store);
|
const result = await update(store);
|
||||||
if (store.accounts.length) await saveAccountStore(store);
|
if (store.accounts.length) await saveAccountStore(store);
|
||||||
else await fs.rm(credentialsPath(), { force: true });
|
else await fs.rm(credentialsPath(), { force: true });
|
||||||
return result;
|
return result;
|
||||||
});
|
});
|
||||||
accountStoreQueue = operation.catch(() => {});
|
accountStoreQueue = operation.catch(() => {});
|
||||||
return operation;
|
return operation;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -175,13 +175,13 @@ async function authorizeOAuthAccount(account) {
|
|||||||
function listOAuthProviders() {
|
function listOAuthProviders() {
|
||||||
return oauth2Service.listProviders();
|
return oauth2Service.listProviders();
|
||||||
}
|
}
|
||||||
|
|
||||||
function sendMailSyncUpdate(update) {
|
function sendMailSyncUpdate(update) {
|
||||||
for (const window of BrowserWindow.getAllWindows()) {
|
for (const window of BrowserWindow.getAllWindows()) {
|
||||||
if (!window.isDestroyed() && !window.webContents.isDestroyed()) {
|
if (!window.isDestroyed() && !window.webContents.isDestroyed()) {
|
||||||
window.webContents.send('mail:sync-update', update);
|
window.webContents.send('mail:sync-update', update);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const { checkSnoozeReminders } = createSnoozeReminderService({
|
const { checkSnoozeReminders } = createSnoozeReminderService({
|
||||||
@@ -197,10 +197,10 @@ const { checkSnoozeReminders } = createSnoozeReminderService({
|
|||||||
},
|
},
|
||||||
sendMailSyncUpdate
|
sendMailSyncUpdate
|
||||||
});
|
});
|
||||||
|
|
||||||
const { createKeyStore } = require('./pgp-keystore.cjs');
|
const { createKeyStore } = require('./pgp-keystore.cjs');
|
||||||
const { createPgpMail, createPassphraseCache, PgpError } = require('./pgp-mail.cjs');
|
const { createPgpMail, createPassphraseCache, PgpError } = require('./pgp-mail.cjs');
|
||||||
|
|
||||||
const pgpKeys = createKeyStore({
|
const pgpKeys = createKeyStore({
|
||||||
async load() {
|
async load() {
|
||||||
try {
|
try {
|
||||||
@@ -212,59 +212,59 @@ const pgpKeys = createKeyStore({
|
|||||||
},
|
},
|
||||||
save(data) { return pgpJsonStore.save(data); }
|
save(data) { return pgpJsonStore.save(data); }
|
||||||
});
|
});
|
||||||
|
|
||||||
const pgpCache = createPassphraseCache(async () => (await pgpKeys.getSettings()).cacheMinutes);
|
const pgpCache = createPassphraseCache(async () => (await pgpKeys.getSettings()).cacheMinutes);
|
||||||
const pgpMail = createPgpMail({ keyStore: pgpKeys, cache: pgpCache });
|
const pgpMail = createPgpMail({ keyStore: pgpKeys, cache: pgpCache });
|
||||||
const pgpKeyServers = createKeyServerService();
|
const pgpKeyServers = createKeyServerService();
|
||||||
const { findSpecialMailbox, findSentMailbox, listCustomFolders, folderPath } = createFolderService({
|
const { findSpecialMailbox, findSentMailbox, listCustomFolders, folderPath } = createFolderService({
|
||||||
customFolderPrefix: CUSTOM_FOLDER_PREFIX,
|
customFolderPrefix: CUSTOM_FOLDER_PREFIX,
|
||||||
isReservedFolderName
|
isReservedFolderName
|
||||||
});
|
});
|
||||||
|
|
||||||
async function readDavStore() {
|
async function readDavStore() {
|
||||||
try {
|
try {
|
||||||
return await davJsonStore.load();
|
return await davJsonStore.load();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (error.code === 'ENOENT') return { caldav: [], carddav: [], activeCaldavId: null, activeCarddavId: null };
|
if (error.code === 'ENOENT') return { caldav: [], carddav: [], activeCaldavId: null, activeCarddavId: null };
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function saveDavStore(store) {
|
async function saveDavStore(store) {
|
||||||
return davJsonStore.save(store);
|
return davJsonStore.save(store);
|
||||||
}
|
}
|
||||||
|
|
||||||
function davPublicConfig(config) {
|
function davPublicConfig(config) {
|
||||||
return { id: config.id, serverUrl: config.serverUrl, username: config.username, collections: config.collections || [] };
|
return { id: config.id, serverUrl: config.serverUrl, username: config.username, collections: config.collections || [] };
|
||||||
}
|
}
|
||||||
|
|
||||||
async function openDavClient(config, type) {
|
async function openDavClient(config, type) {
|
||||||
const { createDAVClient } = await getTsdav();
|
const { createDAVClient } = await getTsdav();
|
||||||
return createDAVClient({ serverUrl: config.serverUrl, credentials: { username: config.username, password: config.password }, authMethod: 'Basic', defaultAccountType: type });
|
return createDAVClient({ serverUrl: config.serverUrl, credentials: { username: config.username, password: config.password }, authMethod: 'Basic', defaultAccountType: type });
|
||||||
}
|
}
|
||||||
|
|
||||||
function activeDavConfig(store, type, id = null) {
|
function activeDavConfig(store, type, id = null) {
|
||||||
const key = type === 'caldav' ? 'caldav' : 'carddav';
|
const key = type === 'caldav' ? 'caldav' : 'carddav';
|
||||||
const activeKey = type === 'caldav' ? 'activeCaldavId' : 'activeCarddavId';
|
const activeKey = type === 'caldav' ? 'activeCaldavId' : 'activeCarddavId';
|
||||||
return store[key].find(item => item.id === (id || store[activeKey])) || null;
|
return store[key].find(item => item.id === (id || store[activeKey])) || null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const { imapClient, smtpTransport } = createMailConnections({
|
const { imapClient, smtpTransport } = createMailConnections({
|
||||||
getImapFlow,
|
getImapFlow,
|
||||||
getNodemailer,
|
getNodemailer,
|
||||||
oauthTokenManager
|
oauthTokenManager
|
||||||
});
|
});
|
||||||
|
|
||||||
function assertSecureStorage() {
|
function assertSecureStorage() {
|
||||||
if (process.platform === 'linux' && typeof safeStorage.getSelectedStorageBackend === 'function') {
|
if (process.platform === 'linux' && typeof safeStorage.getSelectedStorageBackend === 'function') {
|
||||||
const backend = safeStorage.getSelectedStorageBackend();
|
const backend = safeStorage.getSelectedStorageBackend();
|
||||||
if (backend === 'basic_text') {
|
if (backend === 'basic_text') {
|
||||||
throw new Error('This Linux session is using the insecure basic_text password backend. Configure a secure secret store such as gnome-libsecret or kwallet before saving mail credentials or OpenPGP keys.');
|
throw new Error('This Linux session is using the insecure basic_text password backend. Configure a secure secret store such as gnome-libsecret or kwallet before saving mail credentials or OpenPGP keys.');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (!safeStorage.isEncryptionAvailable()) throw new Error('OS credential storage is unavailable.');
|
if (!safeStorage.isEncryptionAvailable()) throw new Error('OS credential storage is unavailable.');
|
||||||
}
|
}
|
||||||
|
|
||||||
async function readAccountStore() {
|
async function readAccountStore() {
|
||||||
return accountRepository.load();
|
return accountRepository.load();
|
||||||
}
|
}
|
||||||
@@ -272,135 +272,135 @@ async function readAccountStore() {
|
|||||||
async function saveAccountStore(store) {
|
async function saveAccountStore(store) {
|
||||||
return accountRepository.save(store);
|
return accountRepository.save(store);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function readAccount(accountId = null) {
|
async function readAccount(accountId = null) {
|
||||||
const store = await readAccountStore();
|
const store = await readAccountStore();
|
||||||
if (!store?.accounts.length) return null;
|
if (!store?.accounts.length) return null;
|
||||||
return store.accounts.find(account => account.id === (accountId || store.activeId)) || null;
|
return store.accounts.find(account => account.id === (accountId || store.activeId)) || null;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function saveAccount(account) {
|
async function saveAccount(account) {
|
||||||
return updateAccountStore(store => {
|
return updateAccountStore(store => {
|
||||||
const existing = store.accounts.find(item => item.email.toLowerCase() === account.email.toLowerCase() && item.imapHost.toLowerCase() === account.imapHost.toLowerCase());
|
const existing = store.accounts.find(item => item.email.toLowerCase() === account.email.toLowerCase() && item.imapHost.toLowerCase() === account.imapHost.toLowerCase());
|
||||||
const saved = { ...existing, ...account, id: existing?.id || randomUUID() };
|
const saved = { ...existing, ...account, id: existing?.id || randomUUID() };
|
||||||
store.accounts = [...store.accounts.filter(item => item.id !== saved.id), saved];
|
store.accounts = [...store.accounts.filter(item => item.id !== saved.id), saved];
|
||||||
store.activeId = saved.id;
|
store.activeId = saved.id;
|
||||||
return saved;
|
return saved;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async function connectMail(account) {
|
async function connectMail(account) {
|
||||||
const client = await imapClient(account);
|
const client = await imapClient(account);
|
||||||
let transport;
|
let transport;
|
||||||
try {
|
try {
|
||||||
await client.connect();
|
await client.connect();
|
||||||
const mailbox = await client.mailboxOpen('INBOX', { readOnly: true });
|
const mailbox = await client.mailboxOpen('INBOX', { readOnly: true });
|
||||||
transport = await smtpTransport(account);
|
transport = await smtpTransport(account);
|
||||||
await transport.verify();
|
await transport.verify();
|
||||||
return { mailbox: mailbox.name, messages: mailbox.exists };
|
return { mailbox: mailbox.name, messages: mailbox.exists };
|
||||||
} finally {
|
} finally {
|
||||||
if (transport) transport.close();
|
if (transport) transport.close();
|
||||||
if (client.usable) await client.logout().catch(() => {});
|
if (client.usable) await client.logout().catch(() => {});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function cacheMailboxMessages(accountId, folder, messages) {
|
async function cacheMailboxMessages(accountId, folder, messages) {
|
||||||
if (!messages.length) return;
|
if (!messages.length) return;
|
||||||
await updateAccountStore(store => {
|
await updateAccountStore(store => {
|
||||||
const account = store.accounts.find(item => item.id === accountId);
|
const account = store.accounts.find(item => item.id === accountId);
|
||||||
if (!account) return;
|
if (!account) return;
|
||||||
account.mailCache = account.mailCache || {};
|
account.mailCache = account.mailCache || {};
|
||||||
const previous = account.mailCache[folder] || [];
|
const previous = account.mailCache[folder] || [];
|
||||||
const merged = new Map(previous.map(message => [String(message.uid || message.id), message]));
|
const merged = new Map(previous.map(message => [String(message.uid || message.id), message]));
|
||||||
for (const message of messages) merged.set(String(message.uid || message.id), message);
|
for (const message of messages) merged.set(String(message.uid || message.id), message);
|
||||||
account.mailCache[folder] = [...merged.values()].slice(-50);
|
account.mailCache[folder] = [...merged.values()].slice(-50);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function cachedMailbox(account, folder, offset = 0, limit = 20, filters = {}) {
|
function cachedMailbox(account, folder, offset = 0, limit = 20, filters = {}) {
|
||||||
const all = filterMailboxMessages(account.mailCache?.[folder] || [], filters)
|
const all = filterMailboxMessages(account.mailCache?.[folder] || [], filters)
|
||||||
.sort((a, b) => Number(b.timestamp || 0) - Number(a.timestamp || 0));
|
.sort((a, b) => Number(b.timestamp || 0) - Number(a.timestamp || 0));
|
||||||
const start = Math.max(0, Number(offset) || 0);
|
const start = Math.max(0, Number(offset) || 0);
|
||||||
const messages = all.slice(start, start + limit);
|
const messages = all.slice(start, start + limit);
|
||||||
return { messages, total: all.length, start: all.length ? start + 1 : 0, end: start + messages.length, folder, offline: true };
|
return { messages, total: all.length, start: all.length ? start + 1 : 0, end: start + messages.length, folder, offline: true };
|
||||||
}
|
}
|
||||||
|
|
||||||
async function toUiMessage(item, folder) {
|
async function toUiMessage(item, folder) {
|
||||||
const { simpleParser } = await getMailparser();
|
const { simpleParser } = await getMailparser();
|
||||||
const parsed = await simpleParser(item.source);
|
const parsed = await simpleParser(item.source);
|
||||||
const sender = parsed.from?.value?.[0];
|
const sender = parsed.from?.value?.[0];
|
||||||
const pgpKind = pgpMail.detect(parsed);
|
const pgpKind = pgpMail.detect(parsed);
|
||||||
const encrypted = pgpKind === 'encrypted-mime' || pgpKind === 'encrypted-inline';
|
const encrypted = pgpKind === 'encrypted-mime' || pgpKind === 'encrypted-inline';
|
||||||
const content = encrypted
|
const content = encrypted
|
||||||
? { bodyText: '', body: ['This message is encrypted with OpenPGP. Open it and enter your key passphrase to read it.'], links: [], attachments: [], attachment: null, size: '' }
|
? { bodyText: '', body: ['This message is encrypted with OpenPGP. Open it and enter your key passphrase to read it.'], links: [], attachments: [], attachment: null, size: '' }
|
||||||
: extractMailContent(parsed);
|
: extractMailContent(parsed);
|
||||||
const { bodyText, body, links } = content;
|
const { bodyText, body, links } = content;
|
||||||
const pgpSignatures = pgpKind && !encrypted ? await pgpMail.verifySigned(parsed, item.source) : null;
|
const pgpSignatures = pgpKind && !encrypted ? await pgpMail.verifySigned(parsed, item.source) : null;
|
||||||
const date = parsed.date || item.internalDate || new Date();
|
const date = parsed.date || item.internalDate || new Date();
|
||||||
return {
|
return {
|
||||||
id: Number(item.uid),
|
id: Number(item.uid),
|
||||||
initials: (sender?.name || sender?.address || '?').split(/[\s@]+/).filter(Boolean).map(word => word[0]).join('').slice(0, 2).toUpperCase(),
|
initials: (sender?.name || sender?.address || '?').split(/[\s@]+/).filter(Boolean).map(word => word[0]).join('').slice(0, 2).toUpperCase(),
|
||||||
color: '#dce6df',
|
color: '#dce6df',
|
||||||
sender: sender?.name || sender?.address || 'Unknown sender',
|
sender: sender?.name || sender?.address || 'Unknown sender',
|
||||||
email: sender?.address || '',
|
email: sender?.address || '',
|
||||||
subject: parsed.subject || '(no subject)',
|
subject: parsed.subject || '(no subject)',
|
||||||
snippet: encrypted ? 'Encrypted message' : (bodyText || parsed.subject || '').replace(/\s+/g, ' ').slice(0, 180),
|
snippet: encrypted ? 'Encrypted message' : (bodyText || parsed.subject || '').replace(/\s+/g, ' ').slice(0, 180),
|
||||||
encrypted,
|
encrypted,
|
||||||
pgpSignatures,
|
pgpSignatures,
|
||||||
time: new Intl.DateTimeFormat(undefined, { hour: 'numeric', minute: '2-digit' }).format(date),
|
time: new Intl.DateTimeFormat(undefined, { hour: 'numeric', minute: '2-digit' }).format(date),
|
||||||
date: new Intl.DateTimeFormat(undefined, { dateStyle: 'medium', timeStyle: 'short' }).format(date),
|
date: new Intl.DateTimeFormat(undefined, { dateStyle: 'medium', timeStyle: 'short' }).format(date),
|
||||||
timestamp: date.getTime(),
|
timestamp: date.getTime(),
|
||||||
unread: !item.flags?.has('\\Seen'),
|
unread: !item.flags?.has('\\Seen'),
|
||||||
star: item.flags?.has('\\Flagged') || false,
|
star: item.flags?.has('\\Flagged') || false,
|
||||||
tags: [folder],
|
tags: [folder],
|
||||||
sent: folder === 'Sent',
|
sent: folder === 'Sent',
|
||||||
archived: folder === 'Archive',
|
archived: folder === 'Archive',
|
||||||
deleted: folder === 'Trash',
|
deleted: folder === 'Trash',
|
||||||
sourceFolder: folder,
|
sourceFolder: folder,
|
||||||
body,
|
body,
|
||||||
html: content.html,
|
html: content.html,
|
||||||
links,
|
links,
|
||||||
uid: Number(item.uid),
|
uid: Number(item.uid),
|
||||||
attachments: content.attachments,
|
attachments: content.attachments,
|
||||||
attachment: content.attachment,
|
attachment: content.attachment,
|
||||||
size: content.size
|
size: content.size
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async function fetchSnoozedMailbox(account, offset, limit) {
|
async function fetchSnoozedMailbox(account, offset, limit) {
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
const pending = (account.snoozedMessages || [])
|
const pending = (account.snoozedMessages || [])
|
||||||
.filter(item => Number(item.dueAt) > now)
|
.filter(item => Number(item.dueAt) > now)
|
||||||
.sort((first, second) => Number(first.dueAt) - Number(second.dueAt));
|
.sort((first, second) => Number(first.dueAt) - Number(second.dueAt));
|
||||||
const selected = pending.slice(Math.max(0, Number(offset) || 0), Math.max(0, Number(offset) || 0) + Math.max(1, Math.min(50, Number(limit) || 20)));
|
const selected = pending.slice(Math.max(0, Number(offset) || 0), Math.max(0, Number(offset) || 0) + Math.max(1, Math.min(50, Number(limit) || 20)));
|
||||||
const client = await imapClient(account);
|
const client = await imapClient(account);
|
||||||
const messages = [];
|
const messages = [];
|
||||||
try {
|
try {
|
||||||
await client.connect();
|
await client.connect();
|
||||||
for (const snooze of selected) {
|
for (const snooze of selected) {
|
||||||
const sourceFolder = String(snooze.folder || 'Inbox');
|
const sourceFolder = String(snooze.folder || 'Inbox');
|
||||||
const mailboxPath = await folderPath(client, sourceFolder);
|
const mailboxPath = await folderPath(client, sourceFolder);
|
||||||
if (!mailboxPath) continue;
|
if (!mailboxPath) continue;
|
||||||
const lock = await client.getMailboxLock(mailboxPath);
|
const lock = await client.getMailboxLock(mailboxPath);
|
||||||
try {
|
try {
|
||||||
const item = await client.fetchOne(Number(snooze.uid), {
|
const item = await client.fetchOne(Number(snooze.uid), {
|
||||||
uid: true, envelope: true, flags: true, internalDate: true, source: true
|
uid: true, envelope: true, flags: true, internalDate: true, source: true
|
||||||
}, { uid: true });
|
}, { uid: true });
|
||||||
if (!item?.source) continue;
|
if (!item?.source) continue;
|
||||||
const message = await toUiMessage(item, 'Snoozed');
|
const message = await toUiMessage(item, 'Snoozed');
|
||||||
message.tags.push(...(account.ruleLabels?.[`${sourceFolder}:${item.uid}`] || []));
|
message.tags.push(...(account.ruleLabels?.[`${sourceFolder}:${item.uid}`] || []));
|
||||||
messages.push({
|
messages.push({
|
||||||
...message,
|
...message,
|
||||||
sourceFolder,
|
sourceFolder,
|
||||||
snoozedUntil: Number(snooze.dueAt)
|
snoozedUntil: Number(snooze.dueAt)
|
||||||
});
|
});
|
||||||
} finally {
|
} finally {
|
||||||
lock.release();
|
lock.release();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
if (client.usable) await client.logout().catch(() => {});
|
if (client.usable) await client.logout().catch(() => {});
|
||||||
}
|
}
|
||||||
return { messages, total: pending.length, start: selected.length ? offset + 1 : 0, end: offset + messages.length, folder: 'Snoozed' };
|
return { messages, total: pending.length, start: selected.length ? offset + 1 : 0, end: offset + messages.length, folder: 'Snoozed' };
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -420,28 +420,28 @@ const { applyMessageAction } = createMessageActionService({
|
|||||||
});
|
});
|
||||||
|
|
||||||
async function saveAccountSyncState(accountId, generation, folders) {
|
async function saveAccountSyncState(accountId, generation, folders) {
|
||||||
return updateAccountStore(store => {
|
return updateAccountStore(store => {
|
||||||
const account = store.accounts.find(item => item.id === accountId);
|
const account = store.accounts.find(item => item.id === accountId);
|
||||||
if (!account || backgroundSyncGenerations.get(accountId) !== generation) return false;
|
if (!account || backgroundSyncGenerations.get(accountId) !== generation) return false;
|
||||||
account.syncState = account.syncState || { folders: {} };
|
account.syncState = account.syncState || { folders: {} };
|
||||||
account.syncState.folders = folders;
|
account.syncState.folders = folders;
|
||||||
return true;
|
return true;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function showNewMailNotification(account, count) {
|
function showNewMailNotification(account, count) {
|
||||||
if (!count || account.notificationsEnabled === false || !Notification.isSupported()) return;
|
if (!count || account.notificationsEnabled === false || !Notification.isSupported()) return;
|
||||||
const focused = BrowserWindow.getAllWindows().some(window => window.isFocused());
|
const focused = BrowserWindow.getAllWindows().some(window => window.isFocused());
|
||||||
if (focused) return;
|
if (focused) return;
|
||||||
const notification = new Notification({
|
const notification = new Notification({
|
||||||
title: count === 1 ? 'New mail' : `${count} new messages`,
|
title: count === 1 ? 'New mail' : `${count} new messages`,
|
||||||
body: account.email
|
body: account.email
|
||||||
});
|
});
|
||||||
notification.show();
|
notification.show();
|
||||||
}
|
}
|
||||||
|
|
||||||
registerIpcHandler('app:get-version', () => app.getVersion());
|
registerIpcHandler('app:get-version', () => app.getVersion());
|
||||||
|
|
||||||
registerPgpIpcHandlers({
|
registerPgpIpcHandlers({
|
||||||
registerIpcHandler,
|
registerIpcHandler,
|
||||||
BrowserWindow,
|
BrowserWindow,
|
||||||
@@ -561,23 +561,23 @@ traceStartup('main services and IPC handlers initialized');
|
|||||||
function createWindow() {
|
function createWindow() {
|
||||||
traceStartup('creating BrowserWindow');
|
traceStartup('creating BrowserWindow');
|
||||||
const window = new BrowserWindow({
|
const window = new BrowserWindow({
|
||||||
width: 1440,
|
width: 1440,
|
||||||
height: 920,
|
height: 920,
|
||||||
minWidth: 920,
|
minWidth: 920,
|
||||||
minHeight: 680,
|
minHeight: 680,
|
||||||
title: `ep-mail v${app.getVersion()}`,
|
title: `ep-mail v${app.getVersion()}`,
|
||||||
backgroundColor: '#f4f5f1',
|
backgroundColor: '#f4f5f1',
|
||||||
show: false,
|
show: false,
|
||||||
autoHideMenuBar: true,
|
autoHideMenuBar: true,
|
||||||
icon: windowsAppIcon || path.join(__dirname, '..', 'icon.svg'),
|
icon: windowsAppIcon || path.join(__dirname, '..', 'icon.svg'),
|
||||||
webPreferences: {
|
webPreferences: {
|
||||||
preload: path.join(__dirname, 'preload.cjs'),
|
preload: path.join(__dirname, 'preload.cjs'),
|
||||||
contextIsolation: true,
|
contextIsolation: true,
|
||||||
nodeIntegration: false,
|
nodeIntegration: false,
|
||||||
sandbox: true
|
sandbox: true
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
window.webContents.on('dom-ready', () => traceStartup('renderer DOM ready'));
|
window.webContents.on('dom-ready', () => traceStartup('renderer DOM ready'));
|
||||||
window.webContents.on('did-finish-load', () => traceStartup('renderer load complete'));
|
window.webContents.on('did-finish-load', () => traceStartup('renderer load complete'));
|
||||||
window.once('ready-to-show', () => {
|
window.once('ready-to-show', () => {
|
||||||
@@ -595,70 +595,70 @@ function createWindow() {
|
|||||||
window.webContents.on('will-navigate', (event, url) => {
|
window.webContents.on('will-navigate', (event, url) => {
|
||||||
if (!isTrustedApplicationUrl(url, applicationHtmlPath)) event.preventDefault();
|
if (!isTrustedApplicationUrl(url, applicationHtmlPath)) event.preventDefault();
|
||||||
});
|
});
|
||||||
return window;
|
return window;
|
||||||
}
|
}
|
||||||
|
|
||||||
function showMainWindow() {
|
function showMainWindow() {
|
||||||
let window = BrowserWindow.getAllWindows().find(item => !item.isDestroyed());
|
let window = BrowserWindow.getAllWindows().find(item => !item.isDestroyed());
|
||||||
if (!window) {
|
if (!window) {
|
||||||
window = createWindow();
|
window = createWindow();
|
||||||
} else {
|
} else {
|
||||||
if (window.isMinimized()) window.restore();
|
if (window.isMinimized()) window.restore();
|
||||||
window.show();
|
window.show();
|
||||||
window.focus();
|
window.focus();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function createWindowsTray() {
|
function createWindowsTray() {
|
||||||
tray = new Tray(windowsAppIcon.resize({ width: 16, height: 16 }));
|
tray = new Tray(windowsAppIcon.resize({ width: 16, height: 16 }));
|
||||||
tray.setToolTip('ep-mail');
|
tray.setToolTip('ep-mail');
|
||||||
tray.setContextMenu(Menu.buildFromTemplate([
|
tray.setContextMenu(Menu.buildFromTemplate([
|
||||||
{ label: 'Open ep-mail', click: showMainWindow },
|
{ label: 'Open ep-mail', click: showMainWindow },
|
||||||
{ type: 'separator' },
|
{ type: 'separator' },
|
||||||
{ label: 'Quit ep-mail', click: () => app.quit() }
|
{ label: 'Quit ep-mail', click: () => app.quit() }
|
||||||
]));
|
]));
|
||||||
tray.on('click', showMainWindow);
|
tray.on('click', showMainWindow);
|
||||||
tray.on('double-click', showMainWindow);
|
tray.on('double-click', showMainWindow);
|
||||||
}
|
}
|
||||||
|
|
||||||
function repairWindowsStartMenuShortcut() {
|
function repairWindowsStartMenuShortcut() {
|
||||||
if (!app.isPackaged) return;
|
if (!app.isPackaged) return;
|
||||||
|
|
||||||
const shortcutPath = path.join(
|
const shortcutPath = path.join(
|
||||||
app.getPath('appData'),
|
app.getPath('appData'),
|
||||||
'Microsoft',
|
'Microsoft',
|
||||||
'Windows',
|
'Windows',
|
||||||
'Start Menu',
|
'Start Menu',
|
||||||
'Programs',
|
'Programs',
|
||||||
'ep-mail.lnk'
|
'ep-mail.lnk'
|
||||||
);
|
);
|
||||||
if (!fsSync.existsSync(shortcutPath)) return;
|
if (!fsSync.existsSync(shortcutPath)) return;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const shortcut = shell.readShortcutLink(shortcutPath);
|
const shortcut = shell.readShortcutLink(shortcutPath);
|
||||||
const isEpMailShortcut = path.basename(shortcut.target).toLowerCase() === 'ep-mail.exe'
|
const isEpMailShortcut = path.basename(shortcut.target).toLowerCase() === 'ep-mail.exe'
|
||||||
|| shortcut.appUserModelId === windowsAppUserModelId;
|
|| shortcut.appUserModelId === windowsAppUserModelId;
|
||||||
if (!isEpMailShortcut) return;
|
if (!isEpMailShortcut) return;
|
||||||
if (shortcut.appUserModelId && shortcut.appUserModelId !== windowsAppUserModelId) return;
|
if (shortcut.appUserModelId && shortcut.appUserModelId !== windowsAppUserModelId) return;
|
||||||
|
|
||||||
const portableExecutable = process.env.PORTABLE_EXECUTABLE_FILE;
|
const portableExecutable = process.env.PORTABLE_EXECUTABLE_FILE;
|
||||||
const executable = portableExecutable && fsSync.existsSync(portableExecutable)
|
const executable = portableExecutable && fsSync.existsSync(portableExecutable)
|
||||||
? portableExecutable
|
? portableExecutable
|
||||||
: process.execPath;
|
: process.execPath;
|
||||||
const updated = shell.writeShortcutLink(shortcutPath, 'update', {
|
const updated = shell.writeShortcutLink(shortcutPath, 'update', {
|
||||||
...shortcut,
|
...shortcut,
|
||||||
target: executable,
|
target: executable,
|
||||||
cwd: path.dirname(executable),
|
cwd: path.dirname(executable),
|
||||||
icon: executable,
|
icon: executable,
|
||||||
iconIndex: 0,
|
iconIndex: 0,
|
||||||
appUserModelId: windowsAppUserModelId
|
appUserModelId: windowsAppUserModelId
|
||||||
});
|
});
|
||||||
if (!updated) throw new Error('Windows did not update the shortcut.');
|
if (!updated) throw new Error('Windows did not update the shortcut.');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Could not repair the ep-mail Start Menu shortcut:', error);
|
console.error('Could not repair the ep-mail Start Menu shortcut:', error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
app.whenReady().then(() => {
|
app.whenReady().then(() => {
|
||||||
traceStartup('Electron app.whenReady');
|
traceStartup('Electron app.whenReady');
|
||||||
app.setAppUserModelId(windowsAppUserModelId);
|
app.setAppUserModelId(windowsAppUserModelId);
|
||||||
@@ -685,17 +685,17 @@ app.whenReady().then(() => {
|
|||||||
snoozeTimer.unref();
|
snoozeTimer.unref();
|
||||||
powerMonitor.on('suspend', () => {
|
powerMonitor.on('suspend', () => {
|
||||||
idleWatcherManager.stopAll();
|
idleWatcherManager.stopAll();
|
||||||
});
|
});
|
||||||
powerMonitor.on('resume', () => requestBackgroundSync(null, true));
|
powerMonitor.on('resume', () => requestBackgroundSync(null, true));
|
||||||
app.on('activate', () => {
|
app.on('activate', () => {
|
||||||
if (BrowserWindow.getAllWindows().length === 0) createWindow();
|
if (BrowserWindow.getAllWindows().length === 0) createWindow();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
app.on('window-all-closed', () => {
|
app.on('window-all-closed', () => {
|
||||||
if (process.platform !== 'darwin') app.quit();
|
if (process.platform !== 'darwin') app.quit();
|
||||||
});
|
});
|
||||||
|
|
||||||
app.on('before-quit', () => {
|
app.on('before-quit', () => {
|
||||||
idleWatcherManager.stopAll();
|
idleWatcherManager.stopAll();
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,277 +1,277 @@
|
|||||||
const openpgp = require('openpgp');
|
const openpgp = require('openpgp');
|
||||||
|
|
||||||
const MAX_KEY_LENGTH = 200000;
|
const MAX_KEY_LENGTH = 200000;
|
||||||
const MAX_RESPONSE_BYTES = 600000;
|
const MAX_RESPONSE_BYTES = 600000;
|
||||||
const REQUEST_TIMEOUT_MS = 15000;
|
const REQUEST_TIMEOUT_MS = 15000;
|
||||||
const MAX_CUSTOM_SERVERS = 10;
|
const MAX_CUSTOM_SERVERS = 10;
|
||||||
|
|
||||||
const BUILTIN_SERVERS = [
|
const BUILTIN_SERVERS = [
|
||||||
{ id: 'openpgp-vks', name: 'keys.openpgp.org', url: 'https://keys.openpgp.org', protocol: 'vks', builtin: true },
|
{ 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 }
|
{ id: 'mailvelope-hkp', name: 'keys.mailvelope.com', url: 'https://keys.mailvelope.com', protocol: 'hkp', builtin: true }
|
||||||
];
|
];
|
||||||
|
|
||||||
function normalizeBaseUrl(value) {
|
function normalizeBaseUrl(value) {
|
||||||
const raw = String(value || '').trim();
|
const raw = String(value || '').trim();
|
||||||
if (raw.length > 300) throw new Error('The key server URL is too long.');
|
if (raw.length > 300) throw new Error('The key server URL is too long.');
|
||||||
let url;
|
let url;
|
||||||
try {
|
try {
|
||||||
url = new URL(raw);
|
url = new URL(raw);
|
||||||
} catch {
|
} catch {
|
||||||
throw new Error('Enter a valid HTTPS key server URL.');
|
throw new Error('Enter a valid HTTPS key server URL.');
|
||||||
}
|
}
|
||||||
if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash) {
|
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.');
|
throw new Error('Key server URLs must use HTTPS and cannot contain credentials, a query, or a fragment.');
|
||||||
}
|
}
|
||||||
url.pathname = `${url.pathname.replace(/\/+$/, '')}/`;
|
url.pathname = `${url.pathname.replace(/\/+$/, '')}/`;
|
||||||
return url.toString();
|
return url.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
function normalizeCustomServer(input) {
|
function normalizeCustomServer(input) {
|
||||||
const name = String(input?.name || '').trim().slice(0, 60);
|
const name = String(input?.name || '').trim().slice(0, 60);
|
||||||
const protocol = input?.protocol;
|
const protocol = input?.protocol;
|
||||||
if (!name) throw new Error('Enter a name for the key server.');
|
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.');
|
if (!['hkp', 'vks'].includes(protocol)) throw new Error('Choose a supported HKP or VKS protocol.');
|
||||||
return {
|
return {
|
||||||
id: String(input?.id || ''),
|
id: String(input?.id || ''),
|
||||||
name,
|
name,
|
||||||
url: normalizeBaseUrl(input?.url),
|
url: normalizeBaseUrl(input?.url),
|
||||||
protocol,
|
protocol,
|
||||||
builtin: false
|
builtin: false
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function listServers(customServers = [], enabledServerIds = []) {
|
function listServers(customServers = [], enabledServerIds = []) {
|
||||||
const enabled = new Set(enabledServerIds);
|
const enabled = new Set(enabledServerIds);
|
||||||
return [
|
return [
|
||||||
...BUILTIN_SERVERS.map(server => ({ ...server, enabled: enabled.has(server.id) })),
|
...BUILTIN_SERVERS.map(server => ({ ...server, enabled: enabled.has(server.id) })),
|
||||||
...customServers.map(server => {
|
...customServers.map(server => {
|
||||||
const normalized = normalizeCustomServer(server);
|
const normalized = normalizeCustomServer(server);
|
||||||
return { ...normalized, enabled: enabled.has(normalized.id) };
|
return { ...normalized, enabled: enabled.has(normalized.id) };
|
||||||
})
|
})
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
function validateEmail(value) {
|
function validateEmail(value) {
|
||||||
const email = String(value || '').trim();
|
const email = String(value || '').trim();
|
||||||
if (!/^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/.test(email)) throw new Error('Enter a valid email address.');
|
if (!/^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/.test(email)) throw new Error('Enter a valid email address.');
|
||||||
return email;
|
return email;
|
||||||
}
|
}
|
||||||
|
|
||||||
function baseUrl(server) {
|
function baseUrl(server) {
|
||||||
return new URL(normalizeBaseUrl(server.url));
|
return new URL(normalizeBaseUrl(server.url));
|
||||||
}
|
}
|
||||||
|
|
||||||
function endpoint(server, path) {
|
function endpoint(server, path) {
|
||||||
return new URL(path, baseUrl(server));
|
return new URL(path, baseUrl(server));
|
||||||
}
|
}
|
||||||
|
|
||||||
async function readResponseText(response) {
|
async function readResponseText(response) {
|
||||||
const declaredLength = Number(response.headers?.get?.('content-length') || 0);
|
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 (declaredLength > MAX_RESPONSE_BYTES) throw new Error('The key server response is too large.');
|
||||||
if (!response.body) return '';
|
if (!response.body) return '';
|
||||||
const chunks = [];
|
const chunks = [];
|
||||||
let length = 0;
|
let length = 0;
|
||||||
for await (const chunk of response.body) {
|
for await (const chunk of response.body) {
|
||||||
const bytes = Buffer.from(chunk);
|
const bytes = Buffer.from(chunk);
|
||||||
length += bytes.length;
|
length += bytes.length;
|
||||||
if (length > MAX_RESPONSE_BYTES) {
|
if (length > MAX_RESPONSE_BYTES) {
|
||||||
throw new Error('The key server response is too large.');
|
throw new Error('The key server response is too large.');
|
||||||
}
|
}
|
||||||
chunks.push(bytes);
|
chunks.push(bytes);
|
||||||
}
|
}
|
||||||
return Buffer.concat(chunks, length).toString('utf8');
|
return Buffer.concat(chunks, length).toString('utf8');
|
||||||
}
|
}
|
||||||
|
|
||||||
function createKeyServerService({ fetchImpl = globalThis.fetch } = {}) {
|
function createKeyServerService({ fetchImpl = globalThis.fetch } = {}) {
|
||||||
if (typeof fetchImpl !== 'function') throw new Error('Fetch is unavailable for key server requests.');
|
if (typeof fetchImpl !== 'function') throw new Error('Fetch is unavailable for key server requests.');
|
||||||
|
|
||||||
async function request(server, url, options = {}) {
|
async function request(server, url, options = {}) {
|
||||||
let response;
|
let response;
|
||||||
try {
|
try {
|
||||||
response = await fetchImpl(url, {
|
response = await fetchImpl(url, {
|
||||||
...options,
|
...options,
|
||||||
redirect: 'error',
|
redirect: 'error',
|
||||||
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
|
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
throw new Error(`Could not reach ${server.name}: ${error.message}`);
|
throw new Error(`Could not reach ${server.name}: ${error.message}`);
|
||||||
}
|
}
|
||||||
const text = await readResponseText(response);
|
const text = await readResponseText(response);
|
||||||
return { response, text };
|
return { response, text };
|
||||||
}
|
}
|
||||||
|
|
||||||
async function parsePublicKeys(armored, email) {
|
async function parsePublicKeys(armored, email) {
|
||||||
if (typeof armored !== 'string' || armored.length > MAX_RESPONSE_BYTES) {
|
if (typeof armored !== 'string' || armored.length > MAX_RESPONSE_BYTES) {
|
||||||
throw new Error('The key server returned an invalid or oversized key response.');
|
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) || [];
|
const blocks = armored.match(/-----BEGIN PGP PUBLIC KEY BLOCK-----[\s\S]*?-----END PGP PUBLIC KEY BLOCK-----/g) || [];
|
||||||
if (!blocks.length) {
|
if (!blocks.length) {
|
||||||
if (!armored.trim() || /no (matching )?keys|no results/i.test(armored)) return [];
|
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.');
|
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.');
|
if (blocks.length > 10) throw new Error('The key server returned too many keys.');
|
||||||
const keys = [];
|
const keys = [];
|
||||||
const seen = new Set();
|
const seen = new Set();
|
||||||
let validKeyCount = 0;
|
let validKeyCount = 0;
|
||||||
for (const block of blocks) {
|
for (const block of blocks) {
|
||||||
if (block.length > MAX_KEY_LENGTH) continue;
|
if (block.length > MAX_KEY_LENGTH) continue;
|
||||||
const key = await openpgp.readKey({ armoredKey: block }).catch(() => null);
|
const key = await openpgp.readKey({ armoredKey: block }).catch(() => null);
|
||||||
if (!key) continue;
|
if (!key) continue;
|
||||||
const fingerprint = key.getFingerprint().toUpperCase();
|
const fingerprint = key.getFingerprint().toUpperCase();
|
||||||
if (seen.has(fingerprint)) continue;
|
if (seen.has(fingerprint)) continue;
|
||||||
seen.add(fingerprint);
|
seen.add(fingerprint);
|
||||||
const emails = [...new Set(key.getUserIDs()
|
const emails = [...new Set(key.getUserIDs()
|
||||||
.map(id => (/<([^>]+)>/.exec(id)?.[1] || (id.includes('@') ? id : '')).trim().toLowerCase())
|
.map(id => (/<([^>]+)>/.exec(id)?.[1] || (id.includes('@') ? id : '')).trim().toLowerCase())
|
||||||
.filter(Boolean))];
|
.filter(Boolean))];
|
||||||
const primary = await key.getPrimaryUser().catch(() => null);
|
const primary = await key.getPrimaryUser().catch(() => null);
|
||||||
if (!primary) continue;
|
if (!primary) continue;
|
||||||
validKeyCount += 1;
|
validKeyCount += 1;
|
||||||
if (email && !emails.includes(email.toLowerCase())) continue;
|
if (email && !emails.includes(email.toLowerCase())) continue;
|
||||||
keys.push({
|
keys.push({
|
||||||
fingerprint,
|
fingerprint,
|
||||||
name: primary.user.userID?.name || '',
|
name: primary.user.userID?.name || '',
|
||||||
emails,
|
emails,
|
||||||
armoredKey: key.armor()
|
armoredKey: key.armor()
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
if (!validKeyCount) throw new Error('The key server returned no valid public keys.');
|
if (!validKeyCount) throw new Error('The key server returned no valid public keys.');
|
||||||
return keys;
|
return keys;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function lookup(serverInput, emailInput) {
|
async function lookup(serverInput, emailInput) {
|
||||||
const server = normalizeCustomServer(serverInput);
|
const server = normalizeCustomServer(serverInput);
|
||||||
const email = validateEmail(emailInput);
|
const email = validateEmail(emailInput);
|
||||||
let url;
|
let url;
|
||||||
if (server.protocol === 'vks') {
|
if (server.protocol === 'vks') {
|
||||||
url = endpoint(server, `vks/v1/by-email/${encodeURIComponent(email)}`);
|
url = endpoint(server, `vks/v1/by-email/${encodeURIComponent(email)}`);
|
||||||
} else {
|
} else {
|
||||||
url = endpoint(server, 'pks/lookup');
|
url = endpoint(server, 'pks/lookup');
|
||||||
url.searchParams.set('op', 'get');
|
url.searchParams.set('op', 'get');
|
||||||
url.searchParams.set('search', email);
|
url.searchParams.set('search', email);
|
||||||
}
|
}
|
||||||
const { response, text } = await request(server, url);
|
const { response, text } = await request(server, url);
|
||||||
if (response.status === 404) return [];
|
if (response.status === 404) return [];
|
||||||
if (!response.ok) throw new Error(`${server.name} returned HTTP ${response.status}.`);
|
if (!response.ok) throw new Error(`${server.name} returned HTTP ${response.status}.`);
|
||||||
let armored = text;
|
let armored = text;
|
||||||
if (server.protocol === 'hkp' && /^\s*\{/.test(text)) {
|
if (server.protocol === 'hkp' && /^\s*\{/.test(text)) {
|
||||||
try {
|
try {
|
||||||
const data = JSON.parse(text);
|
const data = JSON.parse(text);
|
||||||
armored = data.publicKeyArmored || '';
|
armored = data.publicKeyArmored || '';
|
||||||
} catch {
|
} catch {
|
||||||
throw new Error(`${server.name} returned an invalid key response.`);
|
throw new Error(`${server.name} returned an invalid key response.`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return parsePublicKeys(armored, email);
|
return parsePublicKeys(armored, email);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function lookupEnabled(serverInputs, emailInput) {
|
async function lookupEnabled(serverInputs, emailInput) {
|
||||||
const servers = serverInputs.filter(server => server.enabled === true);
|
const servers = serverInputs.filter(server => server.enabled === true);
|
||||||
if (!servers.length) throw new Error('Enable at least one key server before searching.');
|
if (!servers.length) throw new Error('Enable at least one key server before searching.');
|
||||||
const email = validateEmail(emailInput);
|
const email = validateEmail(emailInput);
|
||||||
const lookups = await Promise.all(servers.map(async server => {
|
const lookups = await Promise.all(servers.map(async server => {
|
||||||
try {
|
try {
|
||||||
return { server, keys: await lookup(server, email), error: null };
|
return { server, keys: await lookup(server, email), error: null };
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return { server, keys: [], error: error.message };
|
return { server, keys: [], error: error.message };
|
||||||
}
|
}
|
||||||
}));
|
}));
|
||||||
const keysByFingerprint = new Map();
|
const keysByFingerprint = new Map();
|
||||||
for (const result of lookups) {
|
for (const result of lookups) {
|
||||||
for (const key of result.keys) {
|
for (const key of result.keys) {
|
||||||
const existing = keysByFingerprint.get(key.fingerprint);
|
const existing = keysByFingerprint.get(key.fingerprint);
|
||||||
if (existing) existing.sources.push(result.server.name);
|
if (existing) existing.sources.push(result.server.name);
|
||||||
else keysByFingerprint.set(key.fingerprint, { ...key, sources: [result.server.name] });
|
else keysByFingerprint.set(key.fingerprint, { ...key, sources: [result.server.name] });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
keys: [...keysByFingerprint.values()],
|
keys: [...keysByFingerprint.values()],
|
||||||
searchedServers: lookups.map(({ server }) => ({ id: server.id, name: server.name })),
|
searchedServers: lookups.map(({ server }) => ({ id: server.id, name: server.name })),
|
||||||
errors: lookups.filter(result => result.error).map(({ server, error }) => ({
|
errors: lookups.filter(result => result.error).map(({ server, error }) => ({
|
||||||
id: server.id,
|
id: server.id,
|
||||||
name: server.name,
|
name: server.name,
|
||||||
message: error
|
message: error
|
||||||
}))
|
}))
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async function publishVks(server, email, armoredKey, expectedFingerprint) {
|
async function publishVks(server, email, armoredKey, expectedFingerprint) {
|
||||||
const { response, text } = await request(server, endpoint(server, 'vks/v1/upload'), {
|
const { response, text } = await request(server, endpoint(server, 'vks/v1/upload'), {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'content-type': 'application/json', accept: 'application/json' },
|
headers: { 'content-type': 'application/json', accept: 'application/json' },
|
||||||
body: JSON.stringify({ keytext: armoredKey })
|
body: JSON.stringify({ keytext: armoredKey })
|
||||||
});
|
});
|
||||||
if (!response.ok) throw new Error(`${server.name} rejected the key upload (HTTP ${response.status}).`);
|
if (!response.ok) throw new Error(`${server.name} rejected the key upload (HTTP ${response.status}).`);
|
||||||
let result;
|
let result;
|
||||||
try { result = JSON.parse(text); } catch { throw new Error(`${server.name} returned an invalid upload response.`); }
|
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') {
|
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.`);
|
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];
|
const addressStatus = Object.entries(result.status).find(([address]) => address.toLowerCase() === email.toLowerCase())?.[1];
|
||||||
if (addressStatus === 'published') return { uploaded: true, verification: 'published' };
|
if (addressStatus === 'published') return { uploaded: true, verification: 'published' };
|
||||||
if (addressStatus === 'pending') return { uploaded: true, verification: 'pending' };
|
if (addressStatus === 'pending') return { uploaded: true, verification: 'pending' };
|
||||||
if (addressStatus !== 'unpublished') {
|
if (addressStatus !== 'unpublished') {
|
||||||
return { uploaded: true, verification: addressStatus || 'unknown' };
|
return { uploaded: true, verification: addressStatus || 'unknown' };
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
const verify = await request(server, endpoint(server, 'vks/v1/request-verify'), {
|
const verify = await request(server, endpoint(server, 'vks/v1/request-verify'), {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'content-type': 'application/json', accept: 'application/json' },
|
headers: { 'content-type': 'application/json', accept: 'application/json' },
|
||||||
body: JSON.stringify({ token: result.token, addresses: [email] })
|
body: JSON.stringify({ token: result.token, addresses: [email] })
|
||||||
});
|
});
|
||||||
if (!verify.response.ok) throw new Error(`HTTP ${verify.response.status}`);
|
if (!verify.response.ok) throw new Error(`HTTP ${verify.response.status}`);
|
||||||
let verified;
|
let verified;
|
||||||
try { verified = JSON.parse(verify.text); } catch { throw new Error('invalid verification response'); }
|
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') {
|
if (String(verified.key_fpr || '').toUpperCase() !== expectedFingerprint || !verified.status || typeof verified.status !== 'object') {
|
||||||
throw new Error('verification response did not match the uploaded key');
|
throw new Error('verification response did not match the uploaded key');
|
||||||
}
|
}
|
||||||
const state = Object.entries(verified.status || {}).find(([address]) => address.toLowerCase() === email.toLowerCase())?.[1];
|
const state = Object.entries(verified.status || {}).find(([address]) => address.toLowerCase() === email.toLowerCase())?.[1];
|
||||||
return { uploaded: true, verification: state || 'requested' };
|
return { uploaded: true, verification: state || 'requested' };
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return { uploaded: true, verification: 'request-failed', warning: `The key was uploaded, but email verification could not be requested: ${error.message}` };
|
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) {
|
async function publishHkp(server, armoredKey) {
|
||||||
const form = new URLSearchParams({ keytext: armoredKey });
|
const form = new URLSearchParams({ keytext: armoredKey });
|
||||||
const { response, text } = await request(server, endpoint(server, 'pks/add'), {
|
const { response, text } = await request(server, endpoint(server, 'pks/add'), {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'content-type': 'application/x-www-form-urlencoded' },
|
headers: { 'content-type': 'application/x-www-form-urlencoded' },
|
||||||
body: form.toString()
|
body: form.toString()
|
||||||
});
|
});
|
||||||
if (!response.ok) throw new Error(`${server.name} rejected the key upload (HTTP ${response.status}).`);
|
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)) {
|
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'}`);
|
throw new Error(`${server.name} did not confirm the key upload: ${text.trim().slice(0, 300) || 'empty response'}`);
|
||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
uploaded: true,
|
uploaded: true,
|
||||||
verification: server.id === 'mailvelope-hkp' ? 'check-email' : 'server-accepted',
|
verification: server.id === 'mailvelope-hkp' ? 'check-email' : 'server-accepted',
|
||||||
message: text.trim().slice(0, 500)
|
message: text.trim().slice(0, 500)
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async function publish(serverInput, emailInput, armoredInput, expectedFingerprint) {
|
async function publish(serverInput, emailInput, armoredInput, expectedFingerprint) {
|
||||||
const server = normalizeCustomServer(serverInput);
|
const server = normalizeCustomServer(serverInput);
|
||||||
const email = validateEmail(emailInput);
|
const email = validateEmail(emailInput);
|
||||||
const armoredKey = String(armoredInput || '').trim();
|
const armoredKey = String(armoredInput || '').trim();
|
||||||
if (!armoredKey || armoredKey.length > MAX_KEY_LENGTH || /BEGIN PGP PRIVATE KEY BLOCK/.test(armoredKey)) {
|
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.');
|
throw new Error('Only a valid public key can be published.');
|
||||||
}
|
}
|
||||||
const keys = await parsePublicKeys(armoredKey, email);
|
const keys = await parsePublicKeys(armoredKey, email);
|
||||||
if (keys.length !== 1 || keys[0].fingerprint !== String(expectedFingerprint || '').toUpperCase()) {
|
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.');
|
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);
|
if (server.protocol === 'vks') return publishVks(server, email, keys[0].armoredKey, keys[0].fingerprint);
|
||||||
return publishHkp(server, keys[0].armoredKey);
|
return publishHkp(server, keys[0].armoredKey);
|
||||||
}
|
}
|
||||||
|
|
||||||
return { lookup, lookupEnabled, publish };
|
return { lookup, lookupEnabled, publish };
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
BUILTIN_SERVERS,
|
BUILTIN_SERVERS,
|
||||||
MAX_CUSTOM_SERVERS,
|
MAX_CUSTOM_SERVERS,
|
||||||
createKeyServerService,
|
createKeyServerService,
|
||||||
listServers,
|
listServers,
|
||||||
normalizeBaseUrl,
|
normalizeBaseUrl,
|
||||||
normalizeCustomServer
|
normalizeCustomServer
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,346 +1,346 @@
|
|||||||
const openpgp = require('openpgp');
|
const openpgp = require('openpgp');
|
||||||
|
|
||||||
const MAX_KEY_LENGTH = 200000;
|
const MAX_KEY_LENGTH = 200000;
|
||||||
|
|
||||||
function publicInfo(entry) {
|
function publicInfo(entry) {
|
||||||
return {
|
return {
|
||||||
fingerprint: entry.fingerprint,
|
fingerprint: entry.fingerprint,
|
||||||
name: entry.name,
|
name: entry.name,
|
||||||
email: entry.email,
|
email: entry.email,
|
||||||
accountId: entry.accountId || null,
|
accountId: entry.accountId || null,
|
||||||
createdAt: entry.createdAt,
|
createdAt: entry.createdAt,
|
||||||
algorithm: entry.algorithm,
|
algorithm: entry.algorithm,
|
||||||
hasRevocationCertificate: Boolean(entry.revocationCertificate)
|
hasRevocationCertificate: Boolean(entry.revocationCertificate)
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function requirePassphrase(passphrase) {
|
function requirePassphrase(passphrase) {
|
||||||
if (typeof passphrase !== 'string' || passphrase.length < 8) {
|
if (typeof passphrase !== 'string' || passphrase.length < 8) {
|
||||||
throw new Error('Use a passphrase of at least 8 characters.');
|
throw new Error('Use a passphrase of at least 8 characters.');
|
||||||
}
|
}
|
||||||
return passphrase;
|
return passphrase;
|
||||||
}
|
}
|
||||||
|
|
||||||
function readArmored(value) {
|
function readArmored(value) {
|
||||||
const armored = String(value || '').trim();
|
const armored = String(value || '').trim();
|
||||||
if (!armored || armored.length > MAX_KEY_LENGTH) throw new Error('That key file is empty or too large.');
|
if (!armored || armored.length > MAX_KEY_LENGTH) throw new Error('That key file is empty or too large.');
|
||||||
return armored;
|
return armored;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function unlock(armoredPrivateKey, passphrase) {
|
async function unlock(armoredPrivateKey, passphrase) {
|
||||||
try {
|
try {
|
||||||
return await openpgp.decryptKey({
|
return await openpgp.decryptKey({
|
||||||
privateKey: await openpgp.readPrivateKey({ armoredKey: armoredPrivateKey }),
|
privateKey: await openpgp.readPrivateKey({ armoredKey: armoredPrivateKey }),
|
||||||
passphrase
|
passphrase
|
||||||
});
|
});
|
||||||
} catch {
|
} catch {
|
||||||
throw new Error('The passphrase is incorrect.');
|
throw new Error('The passphrase is incorrect.');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const TRUST_LEVELS = ['unknown', 'trusted', 'verified'];
|
const TRUST_LEVELS = ['unknown', 'trusted', 'verified'];
|
||||||
const DEFAULT_CACHE_MINUTES = 10;
|
const DEFAULT_CACHE_MINUTES = 10;
|
||||||
|
|
||||||
function contactInfo(entry) {
|
function contactInfo(entry) {
|
||||||
return {
|
return {
|
||||||
fingerprint: entry.fingerprint,
|
fingerprint: entry.fingerprint,
|
||||||
name: entry.name,
|
name: entry.name,
|
||||||
emails: entry.emails,
|
emails: entry.emails,
|
||||||
trust: entry.trust,
|
trust: entry.trust,
|
||||||
source: entry.source,
|
source: entry.source,
|
||||||
addedAt: entry.addedAt
|
addedAt: entry.addedAt
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async function readPublicOnly(value) {
|
async function readPublicOnly(value) {
|
||||||
const armored = readArmored(value);
|
const armored = readArmored(value);
|
||||||
if (/BEGIN PGP PRIVATE KEY BLOCK/.test(armored)) throw new Error('That file contains a private key. Import public keys only.');
|
if (/BEGIN PGP PRIVATE KEY BLOCK/.test(armored)) throw new Error('That file contains a private key. Import public keys only.');
|
||||||
const key = await openpgp.readKey({ armoredKey: armored }).catch(() => {
|
const key = await openpgp.readKey({ armoredKey: armored }).catch(() => {
|
||||||
throw new Error('That is not a valid OpenPGP public key.');
|
throw new Error('That is not a valid OpenPGP public key.');
|
||||||
});
|
});
|
||||||
await key.getPrimaryUser().catch(() => {
|
await key.getPrimaryUser().catch(() => {
|
||||||
throw new Error('That key is expired, revoked or has no valid user ID.');
|
throw new Error('That key is expired, revoked or has no valid user ID.');
|
||||||
});
|
});
|
||||||
return key;
|
return key;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function keyEmails(key) {
|
async function keyEmails(key) {
|
||||||
return [...new Set(key.getUserIDs().map(id => (/<([^>]+)>/.exec(id)?.[1] || (id.includes('@') ? id : '')).trim().toLowerCase()).filter(Boolean))];
|
return [...new Set(key.getUserIDs().map(id => (/<([^>]+)>/.exec(id)?.[1] || (id.includes('@') ? id : '')).trim().toLowerCase()).filter(Boolean))];
|
||||||
}
|
}
|
||||||
// Passphrase-protected OpenPGP key storage. `storage` persists one JSON object
|
// Passphrase-protected OpenPGP key storage. `storage` persists one JSON object
|
||||||
// (the desktop app wraps it with the OS credential store before writing it).
|
// (the desktop app wraps it with the OS credential store before writing it).
|
||||||
function createKeyStore(storage) {
|
function createKeyStore(storage) {
|
||||||
async function read() {
|
async function read() {
|
||||||
const data = await storage.load();
|
const data = await storage.load();
|
||||||
return {
|
return {
|
||||||
keys: Array.isArray(data?.keys) ? data.keys : [],
|
keys: Array.isArray(data?.keys) ? data.keys : [],
|
||||||
contacts: Array.isArray(data?.contacts) ? data.contacts : [],
|
contacts: Array.isArray(data?.contacts) ? data.contacts : [],
|
||||||
settings: data?.settings && typeof data.settings === 'object' ? data.settings : {}
|
settings: data?.settings && typeof data.settings === 'object' ? data.settings : {}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async function add(entry) {
|
async function add(entry) {
|
||||||
const data = await read();
|
const data = await read();
|
||||||
if (data.keys.some(key => key.fingerprint === entry.fingerprint)) {
|
if (data.keys.some(key => key.fingerprint === entry.fingerprint)) {
|
||||||
throw new Error('That key is already in your keyring.');
|
throw new Error('That key is already in your keyring.');
|
||||||
}
|
}
|
||||||
data.keys.push(entry);
|
data.keys.push(entry);
|
||||||
await storage.save(data);
|
await storage.save(data);
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
async listContacts() {
|
async listContacts() {
|
||||||
return (await read()).contacts.map(contactInfo);
|
return (await read()).contacts.map(contactInfo);
|
||||||
},
|
},
|
||||||
|
|
||||||
async addContact({ armoredKey, source = 'import' }) {
|
async addContact({ armoredKey, source = 'import' }) {
|
||||||
const key = await readPublicOnly(armoredKey);
|
const key = await readPublicOnly(armoredKey);
|
||||||
const fingerprint = key.getFingerprint().toUpperCase();
|
const fingerprint = key.getFingerprint().toUpperCase();
|
||||||
const emails = await keyEmails(key);
|
const emails = await keyEmails(key);
|
||||||
const data = await read();
|
const data = await read();
|
||||||
if (data.keys.some(entry => entry.fingerprint === fingerprint)) throw new Error('That is one of your own keys.');
|
if (data.keys.some(entry => entry.fingerprint === fingerprint)) throw new Error('That is one of your own keys.');
|
||||||
if (data.contacts.some(entry => entry.fingerprint === fingerprint)) throw new Error('That public key is already in your contacts.');
|
if (data.contacts.some(entry => entry.fingerprint === fingerprint)) throw new Error('That public key is already in your contacts.');
|
||||||
const user = await key.getPrimaryUser();
|
const user = await key.getPrimaryUser();
|
||||||
const replaces = data.contacts
|
const replaces = data.contacts
|
||||||
.filter(entry => entry.emails.some(email => emails.includes(email)))
|
.filter(entry => entry.emails.some(email => emails.includes(email)))
|
||||||
.map(entry => entry.fingerprint);
|
.map(entry => entry.fingerprint);
|
||||||
const entry = {
|
const entry = {
|
||||||
fingerprint,
|
fingerprint,
|
||||||
name: user.user.userID?.name || '',
|
name: user.user.userID?.name || '',
|
||||||
emails,
|
emails,
|
||||||
trust: 'unknown',
|
trust: 'unknown',
|
||||||
source: ['import', 'message', 'paste', 'keyserver'].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()
|
||||||
};
|
};
|
||||||
data.contacts.push(entry);
|
data.contacts.push(entry);
|
||||||
await storage.save(data);
|
await storage.save(data);
|
||||||
return { contact: contactInfo(entry), keyChangedFrom: replaces };
|
return { contact: contactInfo(entry), keyChangedFrom: replaces };
|
||||||
},
|
},
|
||||||
|
|
||||||
async setTrust(fingerprint, trust) {
|
async setTrust(fingerprint, trust) {
|
||||||
if (!TRUST_LEVELS.includes(trust)) throw new Error('Unknown trust level.');
|
if (!TRUST_LEVELS.includes(trust)) throw new Error('Unknown trust level.');
|
||||||
const data = await read();
|
const data = await read();
|
||||||
const entry = data.contacts.find(item => item.fingerprint === fingerprint);
|
const entry = data.contacts.find(item => item.fingerprint === fingerprint);
|
||||||
if (!entry) throw new Error('That contact key was not found.');
|
if (!entry) throw new Error('That contact key was not found.');
|
||||||
entry.trust = trust;
|
entry.trust = trust;
|
||||||
await storage.save(data);
|
await storage.save(data);
|
||||||
return contactInfo(entry);
|
return contactInfo(entry);
|
||||||
},
|
},
|
||||||
|
|
||||||
async removeContact(fingerprint) {
|
async removeContact(fingerprint) {
|
||||||
const data = await read();
|
const data = await read();
|
||||||
if (!data.contacts.some(item => item.fingerprint === fingerprint)) throw new Error('That contact key was not found.');
|
if (!data.contacts.some(item => item.fingerprint === fingerprint)) throw new Error('That contact key was not found.');
|
||||||
data.contacts = data.contacts.filter(item => item.fingerprint !== fingerprint);
|
data.contacts = data.contacts.filter(item => item.fingerprint !== fingerprint);
|
||||||
await storage.save(data);
|
await storage.save(data);
|
||||||
return { removed: true };
|
return { removed: true };
|
||||||
},
|
},
|
||||||
|
|
||||||
async exportContact(fingerprint) {
|
async exportContact(fingerprint) {
|
||||||
const entry = (await read()).contacts.find(item => item.fingerprint === fingerprint);
|
const entry = (await read()).contacts.find(item => item.fingerprint === fingerprint);
|
||||||
if (!entry) throw new Error('That contact key was not found.');
|
if (!entry) throw new Error('That contact key was not found.');
|
||||||
return entry.publicKey;
|
return entry.publicKey;
|
||||||
},
|
},
|
||||||
|
|
||||||
// Resolves public keys for recipient addresses (contacts and own keys).
|
// Resolves public keys for recipient addresses (contacts and own keys).
|
||||||
async findRecipientKeys(addresses) {
|
async findRecipientKeys(addresses) {
|
||||||
const data = await read();
|
const data = await read();
|
||||||
const pool = [
|
const pool = [
|
||||||
...data.contacts.map(entry => ({ ...entry, own: false })),
|
...data.contacts.map(entry => ({ ...entry, own: false })),
|
||||||
...data.keys.map(entry => ({ fingerprint: entry.fingerprint, emails: [String(entry.email).toLowerCase()], trust: 'verified', addedAt: entry.createdAt, publicKey: entry.publicKey, own: true }))
|
...data.keys.map(entry => ({ fingerprint: entry.fingerprint, emails: [String(entry.email).toLowerCase()], trust: 'verified', addedAt: entry.createdAt, publicKey: entry.publicKey, own: true }))
|
||||||
];
|
];
|
||||||
const keys = [];
|
const keys = [];
|
||||||
const missing = [];
|
const missing = [];
|
||||||
for (const address of addresses.map(value => String(value).trim().toLowerCase())) {
|
for (const address of addresses.map(value => String(value).trim().toLowerCase())) {
|
||||||
const candidates = pool
|
const candidates = pool
|
||||||
.filter(entry => entry.emails.includes(address))
|
.filter(entry => entry.emails.includes(address))
|
||||||
.sort((a, b) => TRUST_LEVELS.indexOf(b.trust) - TRUST_LEVELS.indexOf(a.trust) || b.addedAt - a.addedAt);
|
.sort((a, b) => TRUST_LEVELS.indexOf(b.trust) - TRUST_LEVELS.indexOf(a.trust) || b.addedAt - a.addedAt);
|
||||||
let usable = null;
|
let usable = null;
|
||||||
for (const candidate of candidates) {
|
for (const candidate of candidates) {
|
||||||
try {
|
try {
|
||||||
const key = await openpgp.readKey({ armoredKey: candidate.publicKey });
|
const key = await openpgp.readKey({ armoredKey: candidate.publicKey });
|
||||||
await key.getEncryptionKey();
|
await key.getEncryptionKey();
|
||||||
usable = { key, fingerprint: candidate.fingerprint, trust: candidate.trust };
|
usable = { key, fingerprint: candidate.fingerprint, trust: candidate.trust };
|
||||||
break;
|
break;
|
||||||
} catch { /* expired or revoked: try the next key */ }
|
} catch { /* expired or revoked: try the next key */ }
|
||||||
}
|
}
|
||||||
if (usable) keys.push({ address, ...usable });
|
if (usable) keys.push({ address, ...usable });
|
||||||
else missing.push(address);
|
else missing.push(address);
|
||||||
}
|
}
|
||||||
return { keys, missing };
|
return { keys, missing };
|
||||||
},
|
},
|
||||||
|
|
||||||
async verificationKeys() {
|
async verificationKeys() {
|
||||||
const data = await read();
|
const data = await read();
|
||||||
const result = [];
|
const result = [];
|
||||||
for (const entry of [...data.contacts.map(item => ({ ...item, own: false })), ...data.keys.map(item => ({ ...item, trust: 'verified', emails: [String(item.email).toLowerCase()], own: true }))]) {
|
for (const entry of [...data.contacts.map(item => ({ ...item, own: false })), ...data.keys.map(item => ({ ...item, trust: 'verified', emails: [String(item.email).toLowerCase()], own: true }))]) {
|
||||||
try {
|
try {
|
||||||
result.push({ key: await openpgp.readKey({ armoredKey: entry.publicKey }), fingerprint: entry.fingerprint, trust: entry.trust, emails: entry.emails, own: entry.own });
|
result.push({ key: await openpgp.readKey({ armoredKey: entry.publicKey }), fingerprint: entry.fingerprint, trust: entry.trust, emails: entry.emails, own: entry.own });
|
||||||
} catch { /* skip unreadable entries */ }
|
} catch { /* skip unreadable entries */ }
|
||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
},
|
},
|
||||||
|
|
||||||
async privateEntries() {
|
async privateEntries() {
|
||||||
return (await read()).keys.map(entry => ({ fingerprint: entry.fingerprint, email: entry.email, name: entry.name, privateKey: entry.privateKey, publicKey: entry.publicKey }));
|
return (await read()).keys.map(entry => ({ fingerprint: entry.fingerprint, email: entry.email, name: entry.name, privateKey: entry.privateKey, publicKey: entry.publicKey }));
|
||||||
},
|
},
|
||||||
|
|
||||||
async unlockKey(fingerprint, passphrase) {
|
async unlockKey(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.');
|
||||||
return unlock(entry.privateKey, passphrase);
|
return unlock(entry.privateKey, passphrase);
|
||||||
},
|
},
|
||||||
|
|
||||||
async getSettings() {
|
async getSettings() {
|
||||||
const settings = (await read()).settings;
|
const settings = (await read()).settings;
|
||||||
return {
|
return {
|
||||||
cacheMinutes: Number.isFinite(settings.cacheMinutes) ? settings.cacheMinutes : DEFAULT_CACHE_MINUTES,
|
cacheMinutes: Number.isFinite(settings.cacheMinutes) ? settings.cacheMinutes : DEFAULT_CACHE_MINUTES,
|
||||||
customKeyServers: Array.isArray(settings.customKeyServers) ? settings.customKeyServers : [],
|
customKeyServers: Array.isArray(settings.customKeyServers) ? settings.customKeyServers : [],
|
||||||
enabledKeyServers: Array.isArray(settings.enabledKeyServers)
|
enabledKeyServers: Array.isArray(settings.enabledKeyServers)
|
||||||
? [...new Set(settings.enabledKeyServers.filter(id => typeof id === 'string'))]
|
? [...new Set(settings.enabledKeyServers.filter(id => typeof id === 'string'))]
|
||||||
: []
|
: []
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
|
|
||||||
async setSettings({ cacheMinutes, customKeyServers, enabledKeyServers }) {
|
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 (customKeyServers !== undefined) {
|
||||||
if (!Array.isArray(customKeyServers) || customKeyServers.length > 10 || customKeyServers.some(server => !server || typeof server !== 'object')) {
|
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.');
|
throw new Error('You can configure up to 10 valid custom key servers.');
|
||||||
}
|
}
|
||||||
data.settings.customKeyServers = customKeyServers.map(server => ({
|
data.settings.customKeyServers = customKeyServers.map(server => ({
|
||||||
id: String(server.id || ''),
|
id: String(server.id || ''),
|
||||||
name: String(server.name || '').slice(0, 60),
|
name: String(server.name || '').slice(0, 60),
|
||||||
url: String(server.url || '').slice(0, 300),
|
url: String(server.url || '').slice(0, 300),
|
||||||
protocol: String(server.protocol || '')
|
protocol: String(server.protocol || '')
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
if (enabledKeyServers !== undefined) {
|
if (enabledKeyServers !== undefined) {
|
||||||
if (!Array.isArray(enabledKeyServers) || enabledKeyServers.length > 12 || enabledKeyServers.some(id => typeof id !== 'string' || !id.trim())) {
|
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.');
|
throw new Error('Choose no more than 12 valid enabled key servers.');
|
||||||
}
|
}
|
||||||
data.settings.enabledKeyServers = [...new Set(enabledKeyServers)];
|
data.settings.enabledKeyServers = [...new Set(enabledKeyServers)];
|
||||||
}
|
}
|
||||||
await storage.save(data);
|
await storage.save(data);
|
||||||
return {
|
return {
|
||||||
cacheMinutes: data.settings.cacheMinutes,
|
cacheMinutes: data.settings.cacheMinutes,
|
||||||
customKeyServers: Array.isArray(data.settings.customKeyServers) ? data.settings.customKeyServers : [],
|
customKeyServers: Array.isArray(data.settings.customKeyServers) ? data.settings.customKeyServers : [],
|
||||||
enabledKeyServers: Array.isArray(data.settings.enabledKeyServers) ? [...data.settings.enabledKeyServers] : []
|
enabledKeyServers: Array.isArray(data.settings.enabledKeyServers) ? [...data.settings.enabledKeyServers] : []
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
|
|
||||||
async list() {
|
async list() {
|
||||||
return (await read()).keys.map(publicInfo);
|
return (await read()).keys.map(publicInfo);
|
||||||
},
|
},
|
||||||
|
|
||||||
async generate({ name, email, passphrase, accountId = null }) {
|
async generate({ name, email, passphrase, accountId = null }) {
|
||||||
const cleanName = String(name || '').trim().slice(0, 100);
|
const cleanName = String(name || '').trim().slice(0, 100);
|
||||||
const cleanEmail = String(email || '').trim();
|
const cleanEmail = String(email || '').trim();
|
||||||
if (!/^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/.test(cleanEmail)) throw new Error('Enter a valid email address for the key.');
|
if (!/^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/.test(cleanEmail)) throw new Error('Enter a valid email address for the key.');
|
||||||
requirePassphrase(passphrase);
|
requirePassphrase(passphrase);
|
||||||
const { privateKey, publicKey, revocationCertificate } = await openpgp.generateKey({
|
const { privateKey, publicKey, revocationCertificate } = await openpgp.generateKey({
|
||||||
type: 'ecc',
|
type: 'ecc',
|
||||||
curve: 'curve25519Legacy',
|
curve: 'curve25519Legacy',
|
||||||
userIDs: [{ name: cleanName || undefined, email: cleanEmail }],
|
userIDs: [{ name: cleanName || undefined, email: cleanEmail }],
|
||||||
passphrase,
|
passphrase,
|
||||||
format: 'armored'
|
format: 'armored'
|
||||||
});
|
});
|
||||||
const key = await openpgp.readKey({ armoredKey: publicKey });
|
const key = await openpgp.readKey({ armoredKey: publicKey });
|
||||||
const entry = {
|
const entry = {
|
||||||
fingerprint: key.getFingerprint().toUpperCase(),
|
fingerprint: key.getFingerprint().toUpperCase(),
|
||||||
name: cleanName,
|
name: cleanName,
|
||||||
email: cleanEmail,
|
email: cleanEmail,
|
||||||
accountId,
|
accountId,
|
||||||
createdAt: Date.now(),
|
createdAt: Date.now(),
|
||||||
algorithm: 'Curve25519',
|
algorithm: 'Curve25519',
|
||||||
privateKey,
|
privateKey,
|
||||||
publicKey,
|
publicKey,
|
||||||
revocationCertificate
|
revocationCertificate
|
||||||
};
|
};
|
||||||
await add(entry);
|
await add(entry);
|
||||||
return { key: publicInfo(entry), revocationCertificate };
|
return { key: publicInfo(entry), revocationCertificate };
|
||||||
},
|
},
|
||||||
|
|
||||||
async import({ armoredKey, passphrase, accountId = null }) {
|
async import({ armoredKey, passphrase, accountId = null }) {
|
||||||
const parsed = await openpgp.readPrivateKey({ armoredKey: readArmored(armoredKey) }).catch(() => {
|
const parsed = await openpgp.readPrivateKey({ armoredKey: readArmored(armoredKey) }).catch(() => {
|
||||||
throw new Error('That is not a valid OpenPGP private key.');
|
throw new Error('That is not a valid OpenPGP private key.');
|
||||||
});
|
});
|
||||||
requirePassphrase(passphrase);
|
requirePassphrase(passphrase);
|
||||||
let protectedKey;
|
let protectedKey;
|
||||||
if (parsed.isDecrypted()) {
|
if (parsed.isDecrypted()) {
|
||||||
protectedKey = await openpgp.encryptKey({ privateKey: parsed, passphrase });
|
protectedKey = await openpgp.encryptKey({ privateKey: parsed, passphrase });
|
||||||
} else {
|
} else {
|
||||||
await unlock(parsed.armor(), passphrase);
|
await unlock(parsed.armor(), passphrase);
|
||||||
protectedKey = parsed;
|
protectedKey = parsed;
|
||||||
}
|
}
|
||||||
const user = await protectedKey.getPrimaryUser().catch(() => null);
|
const user = await protectedKey.getPrimaryUser().catch(() => null);
|
||||||
const entry = {
|
const entry = {
|
||||||
fingerprint: protectedKey.getFingerprint().toUpperCase(),
|
fingerprint: protectedKey.getFingerprint().toUpperCase(),
|
||||||
name: user?.user?.userID?.name || '',
|
name: user?.user?.userID?.name || '',
|
||||||
email: user?.user?.userID?.email || '',
|
email: user?.user?.userID?.email || '',
|
||||||
accountId,
|
accountId,
|
||||||
createdAt: protectedKey.getCreationTime().getTime(),
|
createdAt: protectedKey.getCreationTime().getTime(),
|
||||||
algorithm: protectedKey.getAlgorithmInfo().algorithm,
|
algorithm: protectedKey.getAlgorithmInfo().algorithm,
|
||||||
privateKey: protectedKey.armor(),
|
privateKey: protectedKey.armor(),
|
||||||
publicKey: protectedKey.toPublic().armor(),
|
publicKey: protectedKey.toPublic().armor(),
|
||||||
revocationCertificate: null
|
revocationCertificate: null
|
||||||
};
|
};
|
||||||
await add(entry);
|
await add(entry);
|
||||||
return publicInfo(entry);
|
return publicInfo(entry);
|
||||||
},
|
},
|
||||||
|
|
||||||
async exportPublic(fingerprint) {
|
async exportPublic(fingerprint) {
|
||||||
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.');
|
||||||
return entry.publicKey;
|
return entry.publicKey;
|
||||||
},
|
},
|
||||||
|
|
||||||
async exportPrivate(fingerprint, passphrase) {
|
async exportPrivate(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.');
|
||||||
await unlock(entry.privateKey, passphrase);
|
await unlock(entry.privateKey, passphrase);
|
||||||
return entry.privateKey;
|
return entry.privateKey;
|
||||||
},
|
},
|
||||||
|
|
||||||
async changePassphrase(fingerprint, currentPassphrase, newPassphrase) {
|
async changePassphrase(fingerprint, currentPassphrase, newPassphrase) {
|
||||||
requirePassphrase(newPassphrase);
|
requirePassphrase(newPassphrase);
|
||||||
const data = await read();
|
const data = await read();
|
||||||
const keyIndex = data.keys.findIndex(key => key.fingerprint === fingerprint);
|
const keyIndex = data.keys.findIndex(key => key.fingerprint === fingerprint);
|
||||||
if (keyIndex < 0) throw new Error('That key was not found.');
|
if (keyIndex < 0) throw new Error('That key was not found.');
|
||||||
const entry = data.keys[keyIndex];
|
const entry = data.keys[keyIndex];
|
||||||
const privateKey = await unlock(entry.privateKey, currentPassphrase);
|
const privateKey = await unlock(entry.privateKey, currentPassphrase);
|
||||||
const protectedKey = await openpgp.encryptKey({ privateKey, passphrase: newPassphrase });
|
const protectedKey = await openpgp.encryptKey({ privateKey, passphrase: newPassphrase });
|
||||||
const updated = {
|
const updated = {
|
||||||
...data,
|
...data,
|
||||||
keys: data.keys.map((key, index) => index === keyIndex
|
keys: data.keys.map((key, index) => index === keyIndex
|
||||||
? { ...key, privateKey: protectedKey.armor() }
|
? { ...key, privateKey: protectedKey.armor() }
|
||||||
: key)
|
: key)
|
||||||
};
|
};
|
||||||
await storage.save(updated);
|
await storage.save(updated);
|
||||||
return { changed: true };
|
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.');
|
||||||
if (!entry.revocationCertificate) throw new Error('No revocation certificate is stored for this key.');
|
if (!entry.revocationCertificate) throw new Error('No revocation certificate is stored for this key.');
|
||||||
await unlock(entry.privateKey, passphrase);
|
await unlock(entry.privateKey, passphrase);
|
||||||
return entry.revocationCertificate;
|
return entry.revocationCertificate;
|
||||||
},
|
},
|
||||||
|
|
||||||
async remove(fingerprint, passphrase) {
|
async remove(fingerprint, passphrase) {
|
||||||
const data = await read();
|
const data = await read();
|
||||||
const entry = data.keys.find(key => key.fingerprint === fingerprint);
|
const entry = data.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.');
|
||||||
await unlock(entry.privateKey, passphrase);
|
await unlock(entry.privateKey, passphrase);
|
||||||
data.keys = data.keys.filter(key => key.fingerprint !== fingerprint);
|
data.keys = data.keys.filter(key => key.fingerprint !== fingerprint);
|
||||||
await storage.save(data);
|
await storage.save(data);
|
||||||
return { removed: true };
|
return { removed: true };
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = { createKeyStore };
|
module.exports = { createKeyStore };
|
||||||
|
|||||||
@@ -1,376 +1,376 @@
|
|||||||
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 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-----/;
|
||||||
const CLEARTEXT_SIGNED = /-----BEGIN PGP SIGNED MESSAGE-----[\s\S]+?-----END PGP SIGNATURE-----/;
|
const CLEARTEXT_SIGNED = /-----BEGIN PGP SIGNED MESSAGE-----[\s\S]+?-----END PGP SIGNATURE-----/;
|
||||||
const MAX_ENCRYPTED_BYTES = 60 * 1048576;
|
const MAX_ENCRYPTED_BYTES = 60 * 1048576;
|
||||||
|
|
||||||
class PgpError extends Error {
|
class PgpError extends Error {
|
||||||
constructor(code, message, details = {}) {
|
constructor(code, message, details = {}) {
|
||||||
super(message);
|
super(message);
|
||||||
this.code = code;
|
this.code = code;
|
||||||
this.details = details;
|
this.details = details;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Remembers unlocked-key passphrases in memory only, for a limited time.
|
// Remembers unlocked-key passphrases in memory only, for a limited time.
|
||||||
function createPassphraseCache(getMinutes, now = () => Date.now()) {
|
function createPassphraseCache(getMinutes, now = () => Date.now()) {
|
||||||
const entries = new Map();
|
const entries = new Map();
|
||||||
return {
|
return {
|
||||||
async remember(fingerprint, passphrase) {
|
async remember(fingerprint, passphrase) {
|
||||||
const minutes = await getMinutes();
|
const minutes = await getMinutes();
|
||||||
if (!minutes) { entries.delete(fingerprint); return; }
|
if (!minutes) { entries.delete(fingerprint); return; }
|
||||||
entries.set(fingerprint, { passphrase, expires: now() + minutes * 60000 });
|
entries.set(fingerprint, { passphrase, expires: now() + minutes * 60000 });
|
||||||
},
|
},
|
||||||
get(fingerprint) {
|
get(fingerprint) {
|
||||||
const entry = entries.get(fingerprint);
|
const entry = entries.get(fingerprint);
|
||||||
if (!entry) return null;
|
if (!entry) return null;
|
||||||
if (entry.expires <= now()) { entries.delete(fingerprint); return null; }
|
if (entry.expires <= now()) { entries.delete(fingerprint); return null; }
|
||||||
return entry.passphrase;
|
return entry.passphrase;
|
||||||
},
|
},
|
||||||
has(fingerprint) { return this.get(fingerprint) !== null; },
|
has(fingerprint) { return this.get(fingerprint) !== null; },
|
||||||
clear(fingerprint) { if (fingerprint) entries.delete(fingerprint); else entries.clear(); }
|
clear(fingerprint) { if (fingerprint) entries.delete(fingerprint); else entries.clear(); }
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function headerValue(parsed, name) {
|
function headerValue(parsed, name) {
|
||||||
const value = parsed.headers?.get(name);
|
const value = parsed.headers?.get(name);
|
||||||
return value && typeof value === 'object' ? value : { value: String(value || ''), params: {} };
|
return value && typeof value === 'object' ? value : { value: String(value || ''), params: {} };
|
||||||
}
|
}
|
||||||
|
|
||||||
// Classifies a parsed message: encrypted/signed PGP/MIME or inline PGP.
|
// Classifies a parsed message: encrypted/signed PGP/MIME or inline PGP.
|
||||||
function detect(parsed) {
|
function detect(parsed) {
|
||||||
const type = String(headerValue(parsed, 'content-type').value).toLowerCase();
|
const type = String(headerValue(parsed, 'content-type').value).toLowerCase();
|
||||||
const protocol = String(headerValue(parsed, 'content-type').params?.protocol || '').toLowerCase();
|
const protocol = String(headerValue(parsed, 'content-type').params?.protocol || '').toLowerCase();
|
||||||
if (type === 'multipart/encrypted' && protocol === 'application/pgp-encrypted') return 'encrypted-mime';
|
if (type === 'multipart/encrypted' && protocol === 'application/pgp-encrypted') return 'encrypted-mime';
|
||||||
if (type === 'multipart/signed' && protocol === 'application/pgp-signature') return 'signed-mime';
|
if (type === 'multipart/signed' && protocol === 'application/pgp-signature') return 'signed-mime';
|
||||||
const text = String(parsed.text || '');
|
const text = String(parsed.text || '');
|
||||||
if (ARMORED_MESSAGE.test(text)) return 'encrypted-inline';
|
if (ARMORED_MESSAGE.test(text)) return 'encrypted-inline';
|
||||||
if (CLEARTEXT_SIGNED.test(text)) return 'signed-inline';
|
if (CLEARTEXT_SIGNED.test(text)) return 'signed-inline';
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
function encryptedArmor(parsed, kind) {
|
function encryptedArmor(parsed, kind) {
|
||||||
if (kind === 'encrypted-inline') return ARMORED_MESSAGE.exec(String(parsed.text || ''))[0];
|
if (kind === 'encrypted-inline') return ARMORED_MESSAGE.exec(String(parsed.text || ''))[0];
|
||||||
for (const file of parsed.attachments || []) {
|
for (const file of parsed.attachments || []) {
|
||||||
const content = file.content.toString('latin1');
|
const content = file.content.toString('latin1');
|
||||||
const match = ARMORED_MESSAGE.exec(content);
|
const match = ARMORED_MESSAGE.exec(content);
|
||||||
if (match) return match[0];
|
if (match) return match[0];
|
||||||
}
|
}
|
||||||
throw new PgpError('CORRUPT', 'The encrypted part of this message is missing or damaged.');
|
throw new PgpError('CORRUPT', 'The encrypted part of this message is missing or damaged.');
|
||||||
}
|
}
|
||||||
|
|
||||||
function emailsOf(key) {
|
function emailsOf(key) {
|
||||||
return key.getUserIDs().map(id => (/<([^>]+)>/.exec(id)?.[1] || (id.includes('@') ? id : '')).trim().toLowerCase()).filter(Boolean);
|
return key.getUserIDs().map(id => (/<([^>]+)>/.exec(id)?.[1] || (id.includes('@') ? id : '')).trim().toLowerCase()).filter(Boolean);
|
||||||
}
|
}
|
||||||
|
|
||||||
function fingerprintsByKeyId(verification) {
|
function fingerprintsByKeyId(verification) {
|
||||||
const map = new Map();
|
const map = new Map();
|
||||||
for (const item of verification) {
|
for (const item of verification) {
|
||||||
for (const key of item.key.getKeys()) map.set(key.getKeyID().toHex().toUpperCase(), item);
|
for (const key of item.key.getKeys()) map.set(key.getKeyID().toHex().toUpperCase(), item);
|
||||||
}
|
}
|
||||||
return map;
|
return map;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Interprets signature results and flags a sender whose key changed.
|
// Interprets signature results and flags a sender whose key changed.
|
||||||
async function describeSignatures(signatures, verification, senderEmail) {
|
async function describeSignatures(signatures, verification, senderEmail) {
|
||||||
const byKeyId = fingerprintsByKeyId(verification);
|
const byKeyId = fingerprintsByKeyId(verification);
|
||||||
const sender = String(senderEmail || '').toLowerCase();
|
const sender = String(senderEmail || '').toLowerCase();
|
||||||
const results = [];
|
const results = [];
|
||||||
for (const signature of signatures) {
|
for (const signature of signatures) {
|
||||||
const keyId = signature.keyID.toHex().toUpperCase();
|
const keyId = signature.keyID.toHex().toUpperCase();
|
||||||
const known = byKeyId.get(keyId);
|
const known = byKeyId.get(keyId);
|
||||||
let status;
|
let status;
|
||||||
try {
|
try {
|
||||||
await signature.verified;
|
await signature.verified;
|
||||||
status = 'valid';
|
status = 'valid';
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
status = /could not find signing key|no signing key|not found/i.test(String(error?.message)) || !known ? 'unknown-key' : 'invalid';
|
status = /could not find signing key|no signing key|not found/i.test(String(error?.message)) || !known ? 'unknown-key' : 'invalid';
|
||||||
}
|
}
|
||||||
const result = { status, keyId, fingerprint: known?.fingerprint || null, trust: known?.trust || null, email: null, matchesSender: false, keyChanged: false };
|
const result = { status, keyId, fingerprint: known?.fingerprint || null, trust: known?.trust || null, email: null, matchesSender: false, keyChanged: false };
|
||||||
if (known) {
|
if (known) {
|
||||||
result.email = known.emails[0] || null;
|
result.email = known.emails[0] || null;
|
||||||
result.matchesSender = Boolean(sender) && known.emails.includes(sender);
|
result.matchesSender = Boolean(sender) && known.emails.includes(sender);
|
||||||
}
|
}
|
||||||
if (sender && status === 'valid' && known && !known.emails.includes(sender)) result.mismatch = true;
|
if (sender && status === 'valid' && known && !known.emails.includes(sender)) result.mismatch = true;
|
||||||
if (sender && status !== 'unknown-key') {
|
if (sender && status !== 'unknown-key') {
|
||||||
const others = verification.filter(item => !item.own && item.emails.includes(sender) && item.fingerprint !== known?.fingerprint);
|
const others = verification.filter(item => !item.own && item.emails.includes(sender) && item.fingerprint !== known?.fingerprint);
|
||||||
if (others.length && !result.matchesSender) result.keyChanged = true;
|
if (others.length && !result.matchesSender) result.keyChanged = true;
|
||||||
}
|
}
|
||||||
if (sender && status === 'unknown-key' && verification.some(item => !item.own && item.emails.includes(sender))) result.keyChanged = true;
|
if (sender && status === 'unknown-key' && verification.some(item => !item.own && item.emails.includes(sender))) result.keyChanged = true;
|
||||||
results.push(result);
|
results.push(result);
|
||||||
}
|
}
|
||||||
return results;
|
return results;
|
||||||
}
|
}
|
||||||
|
|
||||||
function chunkBase64(buffer) {
|
function chunkBase64(buffer) {
|
||||||
return buffer.toString('base64').replace(/(.{76})/g, '$1\r\n').replace(/\r\n$/, '');
|
return buffer.toString('base64').replace(/(.{76})/g, '$1\r\n').replace(/\r\n$/, '');
|
||||||
}
|
}
|
||||||
|
|
||||||
function encodeHeader(value) {
|
function encodeHeader(value) {
|
||||||
const clean = String(value).replace(/[\r\n]+/g, ' ').trim();
|
const clean = String(value).replace(/[\r\n]+/g, ' ').trim();
|
||||||
if (/^[\x20-\x7e]*$/.test(clean) && clean.length <= 900) return clean;
|
if (/^[\x20-\x7e]*$/.test(clean) && clean.length <= 900) return clean;
|
||||||
const chars = Array.from(clean);
|
const chars = Array.from(clean);
|
||||||
const words = [];
|
const words = [];
|
||||||
for (let index = 0; index < chars.length; index += 24) {
|
for (let index = 0; index < chars.length; index += 24) {
|
||||||
words.push(`=?UTF-8?B?${Buffer.from(chars.slice(index, index + 24).join(''), 'utf8').toString('base64')}?=`);
|
words.push(`=?UTF-8?B?${Buffer.from(chars.slice(index, index + 24).join(''), 'utf8').toString('base64')}?=`);
|
||||||
}
|
}
|
||||||
return words.join('\r\n ');
|
return words.join('\r\n ');
|
||||||
}
|
}
|
||||||
|
|
||||||
function formatAddress(entry) {
|
function formatAddress(entry) {
|
||||||
const address = String(entry.address || '').trim();
|
const address = String(entry.address || '').trim();
|
||||||
if (!/^[^\s@<>"',;]+@[^\s@<>"',;]+$/.test(address)) throw new Error(`"${address || entry.name}" is not a valid email address.`);
|
if (!/^[^\s@<>"',;]+@[^\s@<>"',;]+$/.test(address)) throw new Error(`"${address || entry.name}" is not a valid email address.`);
|
||||||
const name = String(entry.name || '').replace(/[\r\n"\\]+/g, ' ').trim();
|
const name = String(entry.name || '').replace(/[\r\n"\\]+/g, ' ').trim();
|
||||||
return name ? `${encodeHeader(`"${name}"`)} <${address}>` : address;
|
return name ? `${encodeHeader(`"${name}"`)} <${address}>` : address;
|
||||||
}
|
}
|
||||||
|
|
||||||
function parseAddresses(value) {
|
function parseAddresses(value) {
|
||||||
return addressParser(String(value || '')).filter(entry => entry.address || entry.name);
|
return addressParser(String(value || '')).filter(entry => entry.address || entry.name);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function innerEntity(text, attachments) {
|
async function innerEntity(text, attachments) {
|
||||||
if (attachments.length) {
|
if (attachments.length) {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
new MailComposer({
|
new MailComposer({
|
||||||
text: String(text || ''),
|
text: String(text || ''),
|
||||||
attachments: attachments.map(file => ({
|
attachments: attachments.map(file => ({
|
||||||
filename: file.filename,
|
filename: file.filename,
|
||||||
contentType: file.contentType,
|
contentType: file.contentType,
|
||||||
content: file.content
|
content: file.content
|
||||||
}))
|
}))
|
||||||
}).compile().build((error, message) => error
|
}).compile().build((error, message) => error
|
||||||
? reject(error)
|
? reject(error)
|
||||||
: resolve(Buffer.from(message.toString('latin1').replace(/\r?\n/g, '\r\n'), 'latin1')));
|
: 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');
|
||||||
}
|
}
|
||||||
|
|
||||||
function boundary() {
|
function boundary() {
|
||||||
return `=_ep-${randomBytes(12).toString('hex')}`;
|
return `=_ep-${randomBytes(12).toString('hex')}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
function createPgpMail({ keyStore, cache }) {
|
function createPgpMail({ keyStore, cache }) {
|
||||||
async function findDecryptionKey(message) {
|
async function findDecryptionKey(message) {
|
||||||
const wanted = new Set(message.getEncryptionKeyIDs().map(id => id.toHex().toUpperCase()));
|
const wanted = new Set(message.getEncryptionKeyIDs().map(id => id.toHex().toUpperCase()));
|
||||||
const entries = await keyStore.privateEntries();
|
const entries = await keyStore.privateEntries();
|
||||||
const candidates = [];
|
const candidates = [];
|
||||||
for (const entry of entries) {
|
for (const entry of entries) {
|
||||||
const publicKey = await openpgp.readKey({ armoredKey: entry.publicKey });
|
const publicKey = await openpgp.readKey({ armoredKey: entry.publicKey });
|
||||||
if (publicKey.getKeys().some(key => wanted.has(key.getKeyID().toHex().toUpperCase()))) candidates.push(entry);
|
if (publicKey.getKeys().some(key => wanted.has(key.getKeyID().toHex().toUpperCase()))) candidates.push(entry);
|
||||||
}
|
}
|
||||||
if (!candidates.length) throw new PgpError('NO_KEY', 'None of your keys can decrypt this message.');
|
if (!candidates.length) throw new PgpError('NO_KEY', 'None of your keys can decrypt this message.');
|
||||||
return candidates;
|
return candidates;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function unlockAny(candidates, passphrase) {
|
async function unlockAny(candidates, passphrase) {
|
||||||
let lastError = null;
|
let lastError = null;
|
||||||
for (const candidate of candidates) {
|
for (const candidate of candidates) {
|
||||||
const secret = passphrase || cache.get(candidate.fingerprint);
|
const secret = passphrase || cache.get(candidate.fingerprint);
|
||||||
if (!secret) continue;
|
if (!secret) continue;
|
||||||
try {
|
try {
|
||||||
const key = await keyStore.unlockKey(candidate.fingerprint, secret);
|
const key = await keyStore.unlockKey(candidate.fingerprint, secret);
|
||||||
await cache.remember(candidate.fingerprint, secret);
|
await cache.remember(candidate.fingerprint, secret);
|
||||||
return key;
|
return key;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
cache.clear(candidate.fingerprint);
|
cache.clear(candidate.fingerprint);
|
||||||
lastError = error;
|
lastError = error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (lastError) throw new PgpError('BAD_PASSPHRASE', 'The passphrase is incorrect.', { fingerprint: candidates[0].fingerprint });
|
if (lastError) throw new PgpError('BAD_PASSPHRASE', 'The passphrase is incorrect.', { fingerprint: candidates[0].fingerprint });
|
||||||
throw new PgpError('PASSPHRASE_REQUIRED', 'Enter your key passphrase to read this message.', {
|
throw new PgpError('PASSPHRASE_REQUIRED', 'Enter your key passphrase to read this message.', {
|
||||||
fingerprint: candidates[0].fingerprint, email: candidates[0].email
|
fingerprint: candidates[0].fingerprint, email: candidates[0].email
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
detect,
|
detect,
|
||||||
|
|
||||||
async decrypt(parsed, { passphrase = null } = {}) {
|
async decrypt(parsed, { passphrase = null } = {}) {
|
||||||
const kind = detect(parsed);
|
const kind = detect(parsed);
|
||||||
if (kind !== 'encrypted-mime' && kind !== 'encrypted-inline') throw new PgpError('NOT_ENCRYPTED', 'This message is not encrypted.');
|
if (kind !== 'encrypted-mime' && kind !== 'encrypted-inline') throw new PgpError('NOT_ENCRYPTED', 'This message is not encrypted.');
|
||||||
const armored = encryptedArmor(parsed, kind);
|
const armored = encryptedArmor(parsed, kind);
|
||||||
if (armored.length > MAX_ENCRYPTED_BYTES) throw new PgpError('TOO_LARGE', 'This encrypted message is too large to open.');
|
if (armored.length > MAX_ENCRYPTED_BYTES) throw new PgpError('TOO_LARGE', 'This encrypted message is too large to open.');
|
||||||
let message;
|
let message;
|
||||||
try {
|
try {
|
||||||
message = await openpgp.readMessage({ armoredMessage: armored });
|
message = await openpgp.readMessage({ armoredMessage: armored });
|
||||||
} catch {
|
} catch {
|
||||||
throw new PgpError('CORRUPT', 'The encrypted part of this message is damaged.');
|
throw new PgpError('CORRUPT', 'The encrypted part of this message is damaged.');
|
||||||
}
|
}
|
||||||
const decryptionKey = await unlockAny(await findDecryptionKey(message), passphrase);
|
const decryptionKey = await unlockAny(await findDecryptionKey(message), passphrase);
|
||||||
const verification = await keyStore.verificationKeys();
|
const verification = await keyStore.verificationKeys();
|
||||||
let result;
|
let result;
|
||||||
try {
|
try {
|
||||||
result = await openpgp.decrypt({
|
result = await openpgp.decrypt({
|
||||||
message,
|
message,
|
||||||
decryptionKeys: decryptionKey,
|
decryptionKeys: decryptionKey,
|
||||||
verificationKeys: verification.map(item => item.key),
|
verificationKeys: verification.map(item => item.key),
|
||||||
format: 'binary'
|
format: 'binary'
|
||||||
});
|
});
|
||||||
} catch {
|
} catch {
|
||||||
throw new PgpError('CORRUPT', 'The message could not be decrypted. It may be damaged or altered.');
|
throw new PgpError('CORRUPT', 'The message could not be decrypted. It may be damaged or altered.');
|
||||||
}
|
}
|
||||||
const data = Buffer.from(result.data);
|
const data = Buffer.from(result.data);
|
||||||
const sender = parsed.from?.value?.[0]?.address || '';
|
const sender = parsed.from?.value?.[0]?.address || '';
|
||||||
const signatures = await describeSignatures(result.signatures, verification, sender);
|
const signatures = await describeSignatures(result.signatures, verification, sender);
|
||||||
const inner = kind === 'encrypted-mime' ? await simpleParser(data) : await simpleParser(Buffer.concat([
|
const inner = kind === 'encrypted-mime' ? await simpleParser(data) : await simpleParser(Buffer.concat([
|
||||||
Buffer.from('Content-Type: text/plain; charset=utf-8\r\n\r\n'), data
|
Buffer.from('Content-Type: text/plain; charset=utf-8\r\n\r\n'), data
|
||||||
]));
|
]));
|
||||||
return { parsed: inner, signatures, attachedKeys: await this.attachedKeys(inner) };
|
return { parsed: inner, signatures, attachedKeys: await this.attachedKeys(inner) };
|
||||||
},
|
},
|
||||||
|
|
||||||
// Public keys attached to a message (offered to the user, never added silently).
|
// Public keys attached to a message (offered to the user, never added silently).
|
||||||
async attachedKeys(parsed) {
|
async attachedKeys(parsed) {
|
||||||
const keys = [];
|
const keys = [];
|
||||||
for (const file of parsed.attachments || []) {
|
for (const file of parsed.attachments || []) {
|
||||||
const type = String(file.contentType || '').toLowerCase();
|
const type = String(file.contentType || '').toLowerCase();
|
||||||
if (type !== 'application/pgp-keys' && !/\.asc$/i.test(file.filename || '')) continue;
|
if (type !== 'application/pgp-keys' && !/\.asc$/i.test(file.filename || '')) continue;
|
||||||
const armored = file.content.toString('utf8');
|
const armored = file.content.toString('utf8');
|
||||||
if (!/BEGIN PGP PUBLIC KEY BLOCK/.test(armored) || armored.length > 200000) continue;
|
if (!/BEGIN PGP PUBLIC KEY BLOCK/.test(armored) || armored.length > 200000) continue;
|
||||||
try {
|
try {
|
||||||
const key = await openpgp.readKey({ armoredKey: armored });
|
const key = await openpgp.readKey({ armoredKey: armored });
|
||||||
keys.push({ armoredKey: armored, fingerprint: key.getFingerprint().toUpperCase(), emails: emailsOf(key) });
|
keys.push({ armoredKey: armored, fingerprint: key.getFingerprint().toUpperCase(), emails: emailsOf(key) });
|
||||||
} catch { /* ignore unreadable attachments */ }
|
} catch { /* ignore unreadable attachments */ }
|
||||||
}
|
}
|
||||||
return keys.slice(0, 5);
|
return keys.slice(0, 5);
|
||||||
},
|
},
|
||||||
|
|
||||||
// Verifies PGP/MIME (multipart/signed) and cleartext signatures on unencrypted mail.
|
// Verifies PGP/MIME (multipart/signed) and cleartext signatures on unencrypted mail.
|
||||||
async verifySigned(parsed, source) {
|
async verifySigned(parsed, source) {
|
||||||
const kind = detect(parsed);
|
const kind = detect(parsed);
|
||||||
const verification = await keyStore.verificationKeys();
|
const verification = await keyStore.verificationKeys();
|
||||||
const sender = parsed.from?.value?.[0]?.address || '';
|
const sender = parsed.from?.value?.[0]?.address || '';
|
||||||
try {
|
try {
|
||||||
if (kind === 'signed-inline') {
|
if (kind === 'signed-inline') {
|
||||||
const message = await openpgp.readCleartextMessage({ cleartextMessage: CLEARTEXT_SIGNED.exec(String(parsed.text))[0] });
|
const message = await openpgp.readCleartextMessage({ cleartextMessage: CLEARTEXT_SIGNED.exec(String(parsed.text))[0] });
|
||||||
const result = await openpgp.verify({ message, verificationKeys: verification.map(item => item.key) });
|
const result = await openpgp.verify({ message, verificationKeys: verification.map(item => item.key) });
|
||||||
return describeSignatures(result.signatures, verification, sender);
|
return describeSignatures(result.signatures, verification, sender);
|
||||||
}
|
}
|
||||||
if (kind !== 'signed-mime') return null;
|
if (kind !== 'signed-mime') return null;
|
||||||
const parts = splitSigned(source, headerValue(parsed, 'content-type').params?.boundary);
|
const parts = splitSigned(source, headerValue(parsed, 'content-type').params?.boundary);
|
||||||
if (!parts) return [{ status: 'invalid', keyId: '', fingerprint: null, trust: null, email: null, matchesSender: false, keyChanged: false }];
|
if (!parts) return [{ status: 'invalid', keyId: '', fingerprint: null, trust: null, email: null, matchesSender: false, keyChanged: false }];
|
||||||
const signature = await openpgp.readSignature({ armoredSignature: parts.signature });
|
const signature = await openpgp.readSignature({ armoredSignature: parts.signature });
|
||||||
const result = await openpgp.verify({
|
const result = await openpgp.verify({
|
||||||
message: await openpgp.createMessage({ binary: parts.signed }),
|
message: await openpgp.createMessage({ binary: parts.signed }),
|
||||||
signature,
|
signature,
|
||||||
verificationKeys: verification.map(item => item.key)
|
verificationKeys: verification.map(item => item.key)
|
||||||
});
|
});
|
||||||
return describeSignatures(result.signatures, verification, sender);
|
return describeSignatures(result.signatures, verification, sender);
|
||||||
} catch {
|
} catch {
|
||||||
return [{ status: 'invalid', keyId: '', fingerprint: null, trust: null, email: null, matchesSender: false, keyChanged: false }];
|
return [{ status: 'invalid', keyId: '', fingerprint: null, trust: null, email: null, matchesSender: false, keyChanged: false }];
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
// 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, attachments = [] }) {
|
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.');
|
||||||
const everyone = [...toList, ...ccList];
|
const everyone = [...toList, ...ccList];
|
||||||
everyone.forEach(entry => formatAddress(entry));
|
everyone.forEach(entry => formatAddress(entry));
|
||||||
let signingKey = null;
|
let signingKey = null;
|
||||||
let signerEntry = null;
|
let signerEntry = null;
|
||||||
if (sign) {
|
if (sign) {
|
||||||
const entries = await keyStore.privateEntries();
|
const entries = await keyStore.privateEntries();
|
||||||
signerEntry = entries.find(entry => entry.fingerprint === signerFingerprint)
|
signerEntry = entries.find(entry => entry.fingerprint === signerFingerprint)
|
||||||
|| entries.find(entry => entry.email.toLowerCase() === String(from.address).toLowerCase());
|
|| entries.find(entry => entry.email.toLowerCase() === String(from.address).toLowerCase());
|
||||||
if (!signerEntry) throw new PgpError('NO_SIGNING_KEY', 'Create or import an encryption key for this address first.');
|
if (!signerEntry) throw new PgpError('NO_SIGNING_KEY', 'Create or import an encryption key for this address first.');
|
||||||
const secret = passphrase || cache.get(signerEntry.fingerprint);
|
const secret = passphrase || cache.get(signerEntry.fingerprint);
|
||||||
if (!secret) throw new PgpError('PASSPHRASE_REQUIRED', 'Enter your key passphrase to sign this message.', { fingerprint: signerEntry.fingerprint, email: signerEntry.email });
|
if (!secret) throw new PgpError('PASSPHRASE_REQUIRED', 'Enter your key passphrase to sign this message.', { fingerprint: signerEntry.fingerprint, email: signerEntry.email });
|
||||||
try {
|
try {
|
||||||
signingKey = await keyStore.unlockKey(signerEntry.fingerprint, secret);
|
signingKey = await keyStore.unlockKey(signerEntry.fingerprint, secret);
|
||||||
} catch {
|
} catch {
|
||||||
cache.clear(signerEntry.fingerprint);
|
cache.clear(signerEntry.fingerprint);
|
||||||
throw new PgpError('BAD_PASSPHRASE', 'The passphrase is incorrect.', { fingerprint: signerEntry.fingerprint });
|
throw new PgpError('BAD_PASSPHRASE', 'The passphrase is incorrect.', { fingerprint: signerEntry.fingerprint });
|
||||||
}
|
}
|
||||||
await cache.remember(signerEntry.fingerprint, secret);
|
await cache.remember(signerEntry.fingerprint, secret);
|
||||||
}
|
}
|
||||||
const headers = [
|
const headers = [
|
||||||
`From: ${formatAddress(from)}`,
|
`From: ${formatAddress(from)}`,
|
||||||
`To: ${toList.map(formatAddress).join(', ')}`,
|
`To: ${toList.map(formatAddress).join(', ')}`,
|
||||||
...(ccList.length ? [`Cc: ${ccList.map(formatAddress).join(', ')}`] : []),
|
...(ccList.length ? [`Cc: ${ccList.map(formatAddress).join(', ')}`] : []),
|
||||||
`Subject: ${encodeHeader(subject || '(no subject)')}`,
|
`Subject: ${encodeHeader(subject || '(no subject)')}`,
|
||||||
`Date: ${date.toUTCString().replace('GMT', '+0000')}`,
|
`Date: ${date.toUTCString().replace('GMT', '+0000')}`,
|
||||||
`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 = await innerEntity(text, attachments);
|
const inner = await innerEntity(text, attachments);
|
||||||
const mark = boundary();
|
const mark = boundary();
|
||||||
let body;
|
let body;
|
||||||
let contentType;
|
let contentType;
|
||||||
if (encrypt) {
|
if (encrypt) {
|
||||||
const { keys, missing } = await keyStore.findRecipientKeys(everyone.map(entry => entry.address));
|
const { keys, missing } = await keyStore.findRecipientKeys(everyone.map(entry => entry.address));
|
||||||
if (missing.length) throw new PgpError('NO_RECIPIENT_KEY', `No public key for ${missing.join(', ')}.`, { missing });
|
if (missing.length) throw new PgpError('NO_RECIPIENT_KEY', `No public key for ${missing.join(', ')}.`, { missing });
|
||||||
const own = signerEntry ? [await openpgp.readKey({ armoredKey: signerEntry.publicKey })] : [];
|
const own = signerEntry ? [await openpgp.readKey({ armoredKey: signerEntry.publicKey })] : [];
|
||||||
const ownKeys = own.length ? own : (await keyStore.findRecipientKeys([from.address])).keys.map(item => item.key);
|
const ownKeys = own.length ? own : (await keyStore.findRecipientKeys([from.address])).keys.map(item => item.key);
|
||||||
const armored = await openpgp.encrypt({
|
const armored = await openpgp.encrypt({
|
||||||
message: await openpgp.createMessage({ binary: inner }),
|
message: await openpgp.createMessage({ binary: inner }),
|
||||||
encryptionKeys: [...keys.map(item => item.key), ...ownKeys],
|
encryptionKeys: [...keys.map(item => item.key), ...ownKeys],
|
||||||
signingKeys: signingKey || undefined,
|
signingKeys: signingKey || undefined,
|
||||||
format: 'armored'
|
format: 'armored'
|
||||||
});
|
});
|
||||||
contentType = `multipart/encrypted; protocol="application/pgp-encrypted"; boundary="${mark}"`;
|
contentType = `multipart/encrypted; protocol="application/pgp-encrypted"; boundary="${mark}"`;
|
||||||
body = [
|
body = [
|
||||||
`--${mark}`, 'Content-Type: application/pgp-encrypted', 'Content-Description: PGP/MIME version identification', '', 'Version: 1', '',
|
`--${mark}`, 'Content-Type: application/pgp-encrypted', 'Content-Description: PGP/MIME version identification', '', 'Version: 1', '',
|
||||||
`--${mark}`, 'Content-Type: application/octet-stream; name="encrypted.asc"', 'Content-Description: OpenPGP encrypted message',
|
`--${mark}`, 'Content-Type: application/octet-stream; name="encrypted.asc"', 'Content-Description: OpenPGP encrypted message',
|
||||||
'Content-Disposition: inline; filename="encrypted.asc"', '', String(armored).replace(/\r?\n/g, '\r\n').trim(), '', `--${mark}--`, ''
|
'Content-Disposition: inline; filename="encrypted.asc"', '', String(armored).replace(/\r?\n/g, '\r\n').trim(), '', `--${mark}--`, ''
|
||||||
].join('\r\n');
|
].join('\r\n');
|
||||||
} else if (sign) {
|
} else if (sign) {
|
||||||
const signedBytes = inner.subarray(0, inner.length - 2);
|
const signedBytes = inner.subarray(0, inner.length - 2);
|
||||||
const detached = await openpgp.sign({ message: await openpgp.createMessage({ binary: signedBytes }), signingKeys: signingKey, detached: true, format: 'armored' });
|
const detached = await openpgp.sign({ message: await openpgp.createMessage({ binary: signedBytes }), signingKeys: signingKey, detached: true, format: 'armored' });
|
||||||
contentType = `multipart/signed; protocol="application/pgp-signature"; micalg=pgp-sha256; boundary="${mark}"`;
|
contentType = `multipart/signed; protocol="application/pgp-signature"; micalg=pgp-sha256; boundary="${mark}"`;
|
||||||
const signedPart = signedBytes.toString('latin1');
|
const signedPart = signedBytes.toString('latin1');
|
||||||
body = [
|
body = [
|
||||||
`--${mark}`, signedPart, `--${mark}`, 'Content-Type: application/pgp-signature; name="signature.asc"',
|
`--${mark}`, signedPart, `--${mark}`, 'Content-Type: application/pgp-signature; name="signature.asc"',
|
||||||
'Content-Description: OpenPGP digital signature', 'Content-Disposition: attachment; filename="signature.asc"', '',
|
'Content-Description: OpenPGP digital signature', 'Content-Disposition: attachment; filename="signature.asc"', '',
|
||||||
String(detached).replace(/\r?\n/g, '\r\n').trim(), '', `--${mark}--`, ''
|
String(detached).replace(/\r?\n/g, '\r\n').trim(), '', `--${mark}--`, ''
|
||||||
].join('\r\n');
|
].join('\r\n');
|
||||||
} else {
|
} else {
|
||||||
throw new Error('Choose encryption or signing for this message.');
|
throw new Error('Choose encryption or signing for this message.');
|
||||||
}
|
}
|
||||||
const raw = Buffer.from(`${headers.join('\r\n')}\r\nContent-Type: ${contentType}\r\n\r\n${body}`, 'latin1');
|
const raw = Buffer.from(`${headers.join('\r\n')}\r\nContent-Type: ${contentType}\r\n\r\n${body}`, 'latin1');
|
||||||
return { raw, envelope: { from: from.address, to: everyone.map(entry => entry.address) }, signerFingerprint: signerEntry?.fingerprint || null };
|
return { raw, envelope: { from: from.address, to: everyone.map(entry => entry.address) }, signerFingerprint: signerEntry?.fingerprint || null };
|
||||||
},
|
},
|
||||||
|
|
||||||
async recipientStatus(addresses, { sign = false, from = '' } = {}) {
|
async recipientStatus(addresses, { sign = false, from = '' } = {}) {
|
||||||
const list = addresses.flatMap(value => parseAddresses(value)).map(entry => entry.address).filter(Boolean);
|
const list = addresses.flatMap(value => parseAddresses(value)).map(entry => entry.address).filter(Boolean);
|
||||||
const { keys, missing } = await keyStore.findRecipientKeys(list);
|
const { keys, missing } = await keyStore.findRecipientKeys(list);
|
||||||
let signer = null;
|
let signer = null;
|
||||||
if (sign) {
|
if (sign) {
|
||||||
const entries = await keyStore.privateEntries();
|
const entries = await keyStore.privateEntries();
|
||||||
const entry = entries.find(item => item.email.toLowerCase() === String(from).toLowerCase()) || null;
|
const entry = entries.find(item => item.email.toLowerCase() === String(from).toLowerCase()) || null;
|
||||||
if (entry) signer = { fingerprint: entry.fingerprint, email: entry.email, name: entry.name, unlocked: cache.has(entry.fingerprint) };
|
if (entry) signer = { fingerprint: entry.fingerprint, email: entry.email, name: entry.name, unlocked: cache.has(entry.fingerprint) };
|
||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
recipients: keys.map(item => ({ address: item.address, fingerprint: item.fingerprint, trust: item.trust })),
|
recipients: keys.map(item => ({ address: item.address, fingerprint: item.fingerprint, trust: item.trust })),
|
||||||
missing,
|
missing,
|
||||||
signer
|
signer
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Extracts the signed part and detached signature from a multipart/signed source.
|
// Extracts the signed part and detached signature from a multipart/signed source.
|
||||||
function splitSigned(source, boundaryValue) {
|
function splitSigned(source, boundaryValue) {
|
||||||
if (!boundaryValue) return null;
|
if (!boundaryValue) return null;
|
||||||
const text = Buffer.from(source).toString('latin1');
|
const text = Buffer.from(source).toString('latin1');
|
||||||
const escaped = String(boundaryValue).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
const escaped = String(boundaryValue).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||||
const delimiter = new RegExp(`(?:^|\\r?\\n)--${escaped}(--)?[ \\t]*(?=\\r?\\n|$)`, 'g');
|
const delimiter = new RegExp(`(?:^|\\r?\\n)--${escaped}(--)?[ \\t]*(?=\\r?\\n|$)`, 'g');
|
||||||
const marks = [...text.matchAll(delimiter)];
|
const marks = [...text.matchAll(delimiter)];
|
||||||
if (marks.length < 3) return null;
|
if (marks.length < 3) return null;
|
||||||
const contentAfter = mark => {
|
const contentAfter = mark => {
|
||||||
const lineEnd = text.indexOf('\n', mark.index + mark[0].length);
|
const lineEnd = text.indexOf('\n', mark.index + mark[0].length);
|
||||||
return lineEnd < 0 ? text.length : lineEnd + 1;
|
return lineEnd < 0 ? text.length : lineEnd + 1;
|
||||||
};
|
};
|
||||||
const signed = text.slice(contentAfter(marks[0]), marks[1].index).replace(/\r?\n/g, '\r\n');
|
const signed = text.slice(contentAfter(marks[0]), marks[1].index).replace(/\r?\n/g, '\r\n');
|
||||||
const signaturePart = text.slice(contentAfter(marks[1]), marks[2].index);
|
const signaturePart = text.slice(contentAfter(marks[1]), marks[2].index);
|
||||||
const armored = /-----BEGIN PGP SIGNATURE-----[\s\S]+?-----END PGP SIGNATURE-----/.exec(signaturePart)?.[0];
|
const armored = /-----BEGIN PGP SIGNATURE-----[\s\S]+?-----END PGP SIGNATURE-----/.exec(signaturePart)?.[0];
|
||||||
if (!armored) return null;
|
if (!armored) return null;
|
||||||
return { signed: Buffer.from(signed, 'latin1'), signature: armored };
|
return { signed: Buffer.from(signed, 'latin1'), signature: armored };
|
||||||
}
|
}
|
||||||
module.exports = { createPgpMail, createPassphraseCache, detect, PgpError, splitSigned };
|
module.exports = { createPgpMail, createPassphraseCache, detect, PgpError, splitSigned };
|
||||||
|
|||||||
@@ -1,62 +1,62 @@
|
|||||||
const { contextBridge, ipcRenderer } = require('electron');
|
const { contextBridge, ipcRenderer } = require('electron');
|
||||||
|
|
||||||
contextBridge.exposeInMainWorld('daybreakMail', {
|
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'),
|
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),
|
||||||
updateAccount: (id, details) => ipcRenderer.invoke('mail:update-account', id, details),
|
updateAccount: (id, details) => ipcRenderer.invoke('mail:update-account', id, details),
|
||||||
syncFolder: (folder, offset, filters) => ipcRenderer.invoke('mail:sync-folder', folder, offset, filters),
|
syncFolder: (folder, offset, filters) => ipcRenderer.invoke('mail:sync-folder', folder, offset, filters),
|
||||||
listFolders: () => ipcRenderer.invoke('mail:list-folders'),
|
listFolders: () => ipcRenderer.invoke('mail:list-folders'),
|
||||||
createFolder: name => ipcRenderer.invoke('mail:create-folder', { name }),
|
createFolder: name => ipcRenderer.invoke('mail:create-folder', { name }),
|
||||||
listDrafts: () => ipcRenderer.invoke('mail:list-drafts'),
|
listDrafts: () => ipcRenderer.invoke('mail:list-drafts'),
|
||||||
saveDraft: draft => ipcRenderer.invoke('mail:save-draft', draft),
|
saveDraft: draft => ipcRenderer.invoke('mail:save-draft', draft),
|
||||||
deleteDraft: id => ipcRenderer.invoke('mail:delete-draft', id),
|
deleteDraft: id => ipcRenderer.invoke('mail:delete-draft', id),
|
||||||
syncInbox: () => ipcRenderer.invoke('mail:sync-folder', 'INBOX'),
|
syncInbox: () => ipcRenderer.invoke('mail:sync-folder', 'INBOX'),
|
||||||
onSyncUpdate: callback => ipcRenderer.on('mail:sync-update', (_event, update) => callback(update)),
|
onSyncUpdate: callback => ipcRenderer.on('mail:sync-update', (_event, update) => callback(update)),
|
||||||
updateMessage: details => ipcRenderer.invoke('mail:update-message', details),
|
updateMessage: details => ipcRenderer.invoke('mail:update-message', details),
|
||||||
setSnooze: details => ipcRenderer.invoke('mail:set-snooze', details),
|
setSnooze: details => ipcRenderer.invoke('mail:set-snooze', details),
|
||||||
previewAttachment: details => ipcRenderer.invoke('mail:preview-attachment', details),
|
previewAttachment: details => ipcRenderer.invoke('mail:preview-attachment', details),
|
||||||
saveAttachment: details => ipcRenderer.invoke('mail:save-attachment', details),
|
saveAttachment: details => ipcRenderer.invoke('mail:save-attachment', details),
|
||||||
openExternal: url => ipcRenderer.invoke('mail:open-external', url),
|
openExternal: url => ipcRenderer.invoke('mail:open-external', url),
|
||||||
send: message => ipcRenderer.invoke('mail:send', message),
|
send: message => ipcRenderer.invoke('mail:send', message),
|
||||||
disconnect: id => ipcRenderer.invoke('mail:disconnect', id),
|
disconnect: id => ipcRenderer.invoke('mail:disconnect', id),
|
||||||
pgp: {
|
pgp: {
|
||||||
list: () => ipcRenderer.invoke('pgp:list'),
|
list: () => ipcRenderer.invoke('pgp:list'),
|
||||||
generate: details => ipcRenderer.invoke('pgp:generate', details),
|
generate: details => ipcRenderer.invoke('pgp:generate', details),
|
||||||
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),
|
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),
|
||||||
checkSend: details => ipcRenderer.invoke('pgp:check-send', details),
|
checkSend: details => ipcRenderer.invoke('pgp:check-send', details),
|
||||||
contacts: () => ipcRenderer.invoke('pgp:contacts'),
|
contacts: () => ipcRenderer.invoke('pgp:contacts'),
|
||||||
addContact: details => ipcRenderer.invoke('pgp:add-contact', details),
|
addContact: details => ipcRenderer.invoke('pgp:add-contact', details),
|
||||||
setTrust: (fingerprint, trust) => ipcRenderer.invoke('pgp:set-trust', fingerprint, trust),
|
setTrust: (fingerprint, trust) => ipcRenderer.invoke('pgp:set-trust', fingerprint, trust),
|
||||||
removeContact: fingerprint => ipcRenderer.invoke('pgp:remove-contact', fingerprint),
|
removeContact: fingerprint => ipcRenderer.invoke('pgp:remove-contact', fingerprint),
|
||||||
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'),
|
keyServers: () => ipcRenderer.invoke('pgp:key-servers'),
|
||||||
setKeyServerEnabled: (serverId, enabled) => ipcRenderer.invoke('pgp:set-key-server-enabled', { serverId, enabled }),
|
setKeyServerEnabled: (serverId, enabled) => ipcRenderer.invoke('pgp:set-key-server-enabled', { serverId, enabled }),
|
||||||
addKeyServer: server => ipcRenderer.invoke('pgp:add-key-server', server),
|
addKeyServer: server => ipcRenderer.invoke('pgp:add-key-server', server),
|
||||||
removeKeyServer: id => ipcRenderer.invoke('pgp:remove-key-server', id),
|
removeKeyServer: id => ipcRenderer.invoke('pgp:remove-key-server', id),
|
||||||
findKey: details => ipcRenderer.invoke('pgp:find-key', details),
|
findKey: details => ipcRenderer.invoke('pgp:find-key', details),
|
||||||
publishKey: details => ipcRenderer.invoke('pgp:publish-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),
|
||||||
davActivate: (type, id) => ipcRenderer.invoke('dav:activate', { type, id }),
|
davActivate: (type, id) => ipcRenderer.invoke('dav:activate', { type, id }),
|
||||||
davRemove: (type, id) => ipcRenderer.invoke('dav:remove', { type, id }),
|
davRemove: (type, id) => ipcRenderer.invoke('dav:remove', { type, id }),
|
||||||
davSync: type => ipcRenderer.invoke('dav:sync', type),
|
davSync: type => ipcRenderer.invoke('dav:sync', type),
|
||||||
davSaveEvent: event => ipcRenderer.invoke('dav:save-event', event),
|
davSaveEvent: event => ipcRenderer.invoke('dav:save-event', event),
|
||||||
davDeleteEvent: remote => ipcRenderer.invoke('dav:delete-event', remote),
|
davDeleteEvent: remote => ipcRenderer.invoke('dav:delete-event', remote),
|
||||||
davSaveContact: contact => ipcRenderer.invoke('dav:save-contact', contact),
|
davSaveContact: contact => ipcRenderer.invoke('dav:save-contact', contact),
|
||||||
davDeleteContact: remote => ipcRenderer.invoke('dav:delete-contact', remote)
|
davDeleteContact: remote => ipcRenderer.invoke('dav:delete-contact', remote)
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
|
||||||
<rect width="64" height="64" rx="12" fill="#0a0c0b"/>
|
<rect width="64" height="64" rx="12" fill="#0a0c0b"/>
|
||||||
<g fill="none" stroke="#eee9de">
|
<g fill="none" stroke="#eee9de">
|
||||||
<circle cx="32" cy="32" r="27" stroke-width="3"/>
|
<circle cx="32" cy="32" r="27" stroke-width="3"/>
|
||||||
<path d="M32 4v56" stroke-width="4"/>
|
<path d="M32 4v56" stroke-width="4"/>
|
||||||
<ellipse cx="32" cy="18" rx="12" ry="5" stroke-width="3" transform="rotate(22 32 18)"/>
|
<ellipse cx="32" cy="18" rx="12" ry="5" stroke-width="3" transform="rotate(22 32 18)"/>
|
||||||
<ellipse cx="32" cy="46" rx="12" ry="5" stroke-width="3" transform="rotate(-22 32 46)"/>
|
<ellipse cx="32" cy="46" rx="12" ry="5" stroke-width="3" transform="rotate(-22 32 46)"/>
|
||||||
<ellipse cx="32" cy="32" rx="8" ry="8" stroke-width="2" opacity=".75" transform="rotate(45 32 32)"/>
|
<ellipse cx="32" cy="32" rx="8" ry="8" stroke-width="2" opacity=".75" transform="rotate(45 32 32)"/>
|
||||||
</g>
|
</g>
|
||||||
</svg>
|
</svg>
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 552 B After Width: | Height: | Size: 562 B |
@@ -1,67 +1,67 @@
|
|||||||
<!doctype html>
|
<!doctype html>
|
||||||
<html lang="en">
|
<html lang="en">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<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: https:; font-src 'self'; connect-src 'none'; frame-src 'none'; object-src 'none'; base-uri 'none'; form-action '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">
|
||||||
<link rel="stylesheet" href="branding.css">
|
<link rel="stylesheet" href="branding.css">
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div class="app-shell">
|
<div class="app-shell">
|
||||||
<aside class="rail" aria-label="Main navigation">
|
<aside class="rail" aria-label="Main navigation">
|
||||||
<div class="brand-mark" title="ep-mail"><img id="brand-logo" src="logo-ep-daylight.svg" alt="Eternity Project"></div>
|
<div class="brand-mark" title="ep-mail"><img id="brand-logo" src="logo-ep-daylight.svg" alt="Eternity Project"></div>
|
||||||
<button class="rail-button active" data-view="mail" aria-label="Mail"><span>✉</span></button>
|
<button class="rail-button active" data-view="mail" aria-label="Mail"><span>✉</span></button>
|
||||||
<button class="rail-button" data-view="calendar" aria-label="Calendar"><span>▦</span></button>
|
<button class="rail-button" data-view="calendar" aria-label="Calendar"><span>▦</span></button>
|
||||||
<button class="rail-button" data-view="contacts" aria-label="Contacts"><span>♙</span></button>
|
<button class="rail-button" data-view="contacts" aria-label="Contacts"><span>♙</span></button>
|
||||||
<div class="rail-spacer"></div>
|
<div class="rail-spacer"></div>
|
||||||
</aside>
|
</aside>
|
||||||
|
|
||||||
<aside class="sidebar">
|
<aside class="sidebar">
|
||||||
<div class="sidebar-head"><div><p class="eyebrow">YOUR WORKSPACE</p><h1 id="sidebar-title">Inbox</h1></div><button class="icon-button" id="sidebar-menu" aria-label="More options">···</button></div>
|
<div class="sidebar-head"><div><p class="eyebrow">YOUR WORKSPACE</p><h1 id="sidebar-title">Inbox</h1></div><button class="icon-button" id="sidebar-menu" aria-label="More options">···</button></div>
|
||||||
<div class="account-card" id="account-settings" role="button" tabindex="0" title="Set up a mail account"><div class="account-avatar">✉</div><div class="account-info"><strong>Mail accounts</strong><span>Manage connected mailboxes</span></div><span class="online-dot"></span></div>
|
<div class="account-card" id="account-settings" role="button" tabindex="0" title="Set up a mail account"><div class="account-avatar">✉</div><div class="account-info"><strong>Mail accounts</strong><span>Manage connected mailboxes</span></div><span class="online-dot"></span></div>
|
||||||
<div class="section-label folders-head"><span>FOLDERS</span><button class="folder-add" id="add-folder" aria-label="Create folder">+</button></div>
|
<div class="section-label folders-head"><span>FOLDERS</span><button class="folder-add" id="add-folder" aria-label="Create folder">+</button></div>
|
||||||
<nav id="mail-nav" class="folder-nav" aria-label="Mail folders">
|
<nav id="mail-nav" class="folder-nav" aria-label="Mail folders">
|
||||||
<button class="folder active" data-folder="Inbox"><span class="nav-glyph">▣</span><span>Inbox</span></button>
|
<button class="folder active" data-folder="Inbox"><span class="nav-glyph">▣</span><span>Inbox</span></button>
|
||||||
<button class="folder" data-folder="Starred"><span class="nav-glyph">☆</span><span>Starred</span></button>
|
<button class="folder" data-folder="Starred"><span class="nav-glyph">☆</span><span>Starred</span></button>
|
||||||
<button class="folder" data-folder="Snoozed"><span class="nav-glyph">◷</span><span>Snoozed</span></button>
|
<button class="folder" data-folder="Snoozed"><span class="nav-glyph">◷</span><span>Snoozed</span></button>
|
||||||
<button class="folder" data-folder="Sent"><span class="nav-glyph">↗</span><span>Sent</span></button>
|
<button class="folder" data-folder="Sent"><span class="nav-glyph">↗</span><span>Sent</span></button>
|
||||||
<button class="folder" data-folder="Drafts"><span class="nav-glyph">▤</span><span>Drafts</span></button>
|
<button class="folder" data-folder="Drafts"><span class="nav-glyph">▤</span><span>Drafts</span></button>
|
||||||
<button class="folder" data-folder="Archive"><span class="nav-glyph">▱</span><span>Archive</span></button>
|
<button class="folder" data-folder="Archive"><span class="nav-glyph">▱</span><span>Archive</span></button>
|
||||||
<button class="folder" data-folder="Trash"><span class="nav-glyph">⌫</span><span>Trash</span></button>
|
<button class="folder" data-folder="Trash"><span class="nav-glyph">⌫</span><span>Trash</span></button>
|
||||||
<div id="custom-folders"></div>
|
<div id="custom-folders"></div>
|
||||||
</nav>
|
</nav>
|
||||||
<button class="label-link" id="attachments-nav"><span class="nav-glyph">▤</span>Attachments</button>
|
<button class="label-link" id="attachments-nav"><span class="nav-glyph">▤</span>Attachments</button>
|
||||||
<div class="sidebar-divider"></div>
|
<div class="sidebar-divider"></div>
|
||||||
<div class="section-label"><span>LABELS</span><button class="tiny-plus" id="add-label" aria-label="Add label">+</button></div>
|
<div class="section-label"><span>LABELS</span><button class="tiny-plus" id="add-label" aria-label="Add label">+</button></div>
|
||||||
<button class="label-link" data-label="Design"><i class="label-dot dot-amber"></i>Design</button>
|
<button class="label-link" data-label="Design"><i class="label-dot dot-amber"></i>Design</button>
|
||||||
<button class="label-link" data-label="Travel"><i class="label-dot dot-blue"></i>Travel</button>
|
<button class="label-link" data-label="Travel"><i class="label-dot dot-blue"></i>Travel</button>
|
||||||
<button class="label-link" data-label="Personal"><i class="label-dot dot-green"></i>Personal</button>
|
<button class="label-link" data-label="Personal"><i class="label-dot dot-green"></i>Personal</button>
|
||||||
<div id="custom-labels"></div>
|
<div id="custom-labels"></div>
|
||||||
<div class="sidebar-bottom"><div class="storage"><div class="storage-top"><span>Storage</span><span>4.2 / 15 GB</span></div><div class="storage-bar"><i></i></div><small>Plenty of room for the good things.</small></div><button class="settings-button" id="settings-button"><span>⚙</span> Settings</button></div>
|
<div class="sidebar-bottom"><div class="storage"><div class="storage-top"><span>Storage</span><span>4.2 / 15 GB</span></div><div class="storage-bar"><i></i></div><small>Plenty of room for the good things.</small></div><button class="settings-button" id="settings-button"><span>⚙</span> Settings</button></div>
|
||||||
</aside>
|
</aside>
|
||||||
|
|
||||||
<main class="main-area">
|
<main class="main-area">
|
||||||
<header class="topbar"><div class="breadcrumbs"><span id="crumb-parent">Mail</span><span class="crumb-divider">/</span><strong id="crumb-current">Inbox</strong></div><div class="top-actions"><div class="search-wrap"><span>⌕</span><input id="search" placeholder="Search mail" aria-label="Search mail"><kbd>⌘ K</kbd></div><button class="icon-button" id="search-filters-toggle" aria-expanded="false" title="Search filters">☷</button><button class="icon-button help-button" aria-label="Help" title="Help">?</button><button class="avatar top-avatar profile-button" title="Account settings" aria-label="Account settings">•</button><section id="search-filters" class="search-filters hidden" aria-label="Advanced search filters"><label>Folder<select id="filter-folder"><option value="">Current folder</option><option>Inbox</option><option>Sent</option><option>Archive</option><option>Trash</option></select></label><label>From<input id="filter-sender" placeholder="Sender contains"></label><label>Subject<input id="filter-subject" placeholder="Subject contains"></label><label>After<input id="filter-after" type="date"></label><label>Before<input id="filter-before" type="date"></label><label class="filter-checkbox"><input id="filter-attachments" type="checkbox"> Has attachments</label><button id="clear-search-filters" class="text-button">Clear filters</button></section></div></header>
|
<header class="topbar"><div class="breadcrumbs"><span id="crumb-parent">Mail</span><span class="crumb-divider">/</span><strong id="crumb-current">Inbox</strong></div><div class="top-actions"><div class="search-wrap"><span>⌕</span><input id="search" placeholder="Search mail" aria-label="Search mail"><kbd>⌘ K</kbd></div><button class="icon-button" id="search-filters-toggle" aria-expanded="false" title="Search filters">☷</button><button class="icon-button help-button" aria-label="Help" title="Help">?</button><button class="avatar top-avatar profile-button" title="Account settings" aria-label="Account settings">•</button><section id="search-filters" class="search-filters hidden" aria-label="Advanced search filters"><label>Folder<select id="filter-folder"><option value="">Current folder</option><option>Inbox</option><option>Sent</option><option>Archive</option><option>Trash</option></select></label><label>From<input id="filter-sender" placeholder="Sender contains"></label><label>Subject<input id="filter-subject" placeholder="Subject contains"></label><label>After<input id="filter-after" type="date"></label><label>Before<input id="filter-before" type="date"></label><label class="filter-checkbox"><input id="filter-attachments" type="checkbox"> Has attachments</label><button id="clear-search-filters" class="text-button">Clear filters</button></section></div></header>
|
||||||
|
|
||||||
<section id="mail-view" class="content-view mail-layout">
|
<section id="mail-view" class="content-view mail-layout">
|
||||||
<div class="list-pane">
|
<div class="list-pane">
|
||||||
<div class="list-heading"><div><div class="date-line" id="today-label">MONDAY, OCTOBER 4</div><h2 id="welcome-heading">Good morning<span id="greeting-name" hidden></span></h2></div><button class="compose-button" id="compose"><span>+</span> Compose</button></div>
|
<div class="list-heading"><div><div class="date-line" id="today-label">MONDAY, OCTOBER 4</div><h2 id="welcome-heading">Good morning<span id="greeting-name" hidden></span></h2></div><button class="compose-button" id="compose"><span>+</span> Compose</button></div>
|
||||||
<div class="toolbar"><button class="tool-checkbox" id="select-all" aria-label="Select all">□</button><button class="icon-button" id="refresh" title="Refresh">↻</button><span class="toolbar-divider"></span><button class="icon-button" id="archive-selected" title="Archive">▱</button><button class="icon-button" id="delete-selected" title="Delete">⌫</button><button class="icon-button" id="mark-unread" title="Mark unread">✉</button><span class="toolbar-spacer"></span><button class="icon-button" id="previous-page" title="Previous page">‹</button><span class="pagination" id="pagination">1–8 of 24</span><button class="icon-button" id="next-page" title="Next page">›</button></div>
|
<div class="toolbar"><button class="tool-checkbox" id="select-all" aria-label="Select all">□</button><button class="icon-button" id="refresh" title="Refresh">↻</button><span class="toolbar-divider"></span><button class="icon-button" id="archive-selected" title="Archive">▱</button><button class="icon-button" id="delete-selected" title="Delete">⌫</button><button class="icon-button" id="mark-unread" title="Mark unread">✉</button><span class="toolbar-spacer"></span><button class="icon-button" id="previous-page" title="Previous page">‹</button><span class="pagination" id="pagination">1–8 of 24</span><button class="icon-button" id="next-page" title="Next page">›</button></div>
|
||||||
<div class="message-list" id="message-list" aria-label="Messages"></div>
|
<div class="message-list" id="message-list" aria-label="Messages"></div>
|
||||||
<div class="list-foot"><span><i class="online-dot"></i> <span id="mail-status">All caught up with your mail</span></span><button class="text-button" id="load-more">Load more <span>↓</span></button></div>
|
<div class="list-foot"><span><i class="online-dot"></i> <span id="mail-status">All caught up with your mail</span></span><button class="text-button" id="load-more">Load more <span>↓</span></button></div>
|
||||||
</div>
|
</div>
|
||||||
<article class="reader-pane" id="reader-pane"></article>
|
<article class="reader-pane" id="reader-pane"></article>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<section id="calendar-view" class="content-view page-view hidden"></section>
|
<section id="calendar-view" class="content-view page-view hidden"></section>
|
||||||
<section id="contacts-view" class="content-view page-view hidden"></section>
|
<section id="contacts-view" class="content-view page-view hidden"></section>
|
||||||
</main>
|
</main>
|
||||||
</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="renderer-state.js"></script>
|
||||||
@@ -70,13 +70,13 @@
|
|||||||
<script src="platform-bridge-loader.js"></script>
|
<script src="platform-bridge-loader.js"></script>
|
||||||
<script src="renderer-mail-api.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="dav-ui.js"></script>
|
<script src="dav-ui.js"></script>
|
||||||
<script src="account-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>
|
||||||
<script src="pgp-mail-ui.js"></script>
|
<script src="pgp-mail-ui.js"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" aria-hidden="true" focusable="false">
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" aria-hidden="true" focusable="false">
|
||||||
<g fill="none" stroke="#181b19">
|
<g fill="none" stroke="#181b19">
|
||||||
<circle cx="32" cy="32" r="28" stroke-width="2"/>
|
<circle cx="32" cy="32" r="28" stroke-width="2"/>
|
||||||
<path d="M32 3v58" stroke-width="3"/>
|
<path d="M32 3v58" stroke-width="3"/>
|
||||||
<ellipse cx="32" cy="18" rx="12" ry="5" stroke-width="2" transform="rotate(22 32 18)"/>
|
<ellipse cx="32" cy="18" rx="12" ry="5" stroke-width="2" transform="rotate(22 32 18)"/>
|
||||||
<ellipse cx="32" cy="46" rx="12" ry="5" stroke-width="2" transform="rotate(-22 32 46)"/>
|
<ellipse cx="32" cy="46" rx="12" ry="5" stroke-width="2" transform="rotate(-22 32 46)"/>
|
||||||
<ellipse cx="32" cy="32" rx="8" ry="8" stroke-width="1.5" opacity=".6" transform="rotate(45 32 32)"/>
|
<ellipse cx="32" cy="32" rx="8" ry="8" stroke-width="1.5" opacity=".6" transform="rotate(45 32 32)"/>
|
||||||
</g>
|
</g>
|
||||||
</svg>
|
</svg>
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 534 B After Width: | Height: | Size: 543 B |
@@ -1,9 +1,9 @@
|
|||||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" aria-hidden="true" focusable="false">
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" aria-hidden="true" focusable="false">
|
||||||
<g fill="none" stroke="#e7e2d3">
|
<g fill="none" stroke="#e7e2d3">
|
||||||
<circle cx="32" cy="32" r="28" stroke-width="2"/>
|
<circle cx="32" cy="32" r="28" stroke-width="2"/>
|
||||||
<path d="M32 3v58" stroke-width="3"/>
|
<path d="M32 3v58" stroke-width="3"/>
|
||||||
<ellipse cx="32" cy="18" rx="12" ry="5" stroke-width="2" transform="rotate(22 32 18)"/>
|
<ellipse cx="32" cy="18" rx="12" ry="5" stroke-width="2" transform="rotate(22 32 18)"/>
|
||||||
<ellipse cx="32" cy="46" rx="12" ry="5" stroke-width="2" transform="rotate(-22 32 46)"/>
|
<ellipse cx="32" cy="46" rx="12" ry="5" stroke-width="2" transform="rotate(-22 32 46)"/>
|
||||||
<ellipse cx="32" cy="32" rx="8" ry="8" stroke-width="1.5" opacity=".6" transform="rotate(45 32 32)"/>
|
<ellipse cx="32" cy="32" rx="8" ry="8" stroke-width="1.5" opacity=".6" transform="rotate(45 32 32)"/>
|
||||||
</g>
|
</g>
|
||||||
</svg>
|
</svg>
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 534 B After Width: | Height: | Size: 543 B |
@@ -1,10 +1,10 @@
|
|||||||
{
|
{
|
||||||
"name": "ep-mail",
|
"name": "ep-mail",
|
||||||
"short_name": "ep-mail",
|
"short_name": "ep-mail",
|
||||||
"description": "Eternity Project mail, calendar, and contacts.",
|
"description": "Eternity Project mail, calendar, and contacts.",
|
||||||
"start_url": "./",
|
"start_url": "./",
|
||||||
"display": "standalone",
|
"display": "standalone",
|
||||||
"background_color": "#f4f5f1",
|
"background_color": "#f4f5f1",
|
||||||
"theme_color": "#f4f5f1",
|
"theme_color": "#f4f5f1",
|
||||||
"icons": [{"src":"icon.svg","sizes":"any","type":"image/svg+xml","purpose":"any maskable"}]
|
"icons": [{"src":"icon.svg","sizes":"any","type":"image/svg+xml","purpose":"any maskable"}]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,110 +1,111 @@
|
|||||||
{
|
{
|
||||||
"name": "ep-mail",
|
"name": "ep-mail",
|
||||||
"version": "0.5.1",
|
"version": "0.5.2",
|
||||||
"private": true,
|
"private": true,
|
||||||
"description": "Eternity Project mail client",
|
"description": "Eternity Project mail client",
|
||||||
"homepage": "https://git.eternityproject.fi/thuttu/ep-mail-client",
|
"homepage": "https://git.eternityproject.fi/thuttu/ep-mail-client",
|
||||||
"author": {
|
"author": {
|
||||||
"name": "Eternity Project",
|
"name": "Eternity Project",
|
||||||
"email": "tero.huttunen@eternityproject.fi"
|
"email": "tero.huttunen@eternityproject.fi"
|
||||||
},
|
},
|
||||||
"desktopName": "ep-mail",
|
"desktopName": "ep-mail",
|
||||||
"main": "desktop/main.cjs",
|
"main": "desktop/main.cjs",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"start": "electron .",
|
"start": "electron .",
|
||||||
"dev": "electron .",
|
"dev": "electron .",
|
||||||
"dist:win": "electron-builder --win",
|
"dist:win": "electron-builder --win",
|
||||||
"dist:win:installer": "electron-builder --win nsis",
|
"dist:win:installer": "electron-builder --win nsis",
|
||||||
"dist:win:portable": "electron-builder --win portable",
|
"dist:win:portable": "electron-builder --win portable",
|
||||||
"dist:linux": "electron-builder --linux AppImage deb",
|
"dist:linux": "electron-builder --linux AppImage deb",
|
||||||
"dist:linux:appimage": "electron-builder --linux AppImage",
|
"dist:linux:appimage": "electron-builder --linux AppImage",
|
||||||
"dist:linux:deb": "electron-builder --linux deb",
|
"dist:linux:deb": "electron-builder --linux deb",
|
||||||
"bump:build": "npm version patch --no-git-tag-version",
|
"bump:build": "npm version patch --no-git-tag-version",
|
||||||
"test": "node --test tests/",
|
"test": "node --test tests/",
|
||||||
"build:android-web": "node scripts/prepare-android-web.cjs",
|
"build:android-web": "node scripts/prepare-android-web.cjs",
|
||||||
"android:sync": "npm run build:android-web && cap sync android",
|
"android:sync": "npm run build:android-web && cap sync android",
|
||||||
"android:open": "npm run android:sync && cap open android",
|
"android:open": "npm run android:sync && cap open android",
|
||||||
"android:apk": "npm run android:sync && node scripts/build-android-apk.cjs",
|
"android:apk": "npm run android:sync && node scripts/build-android-apk.cjs",
|
||||||
"build:all": "powershell -NoProfile -ExecutionPolicy Bypass -File scripts/build-all.ps1"
|
"android:release-apk": "npm run android:sync && node scripts/build-android-release-apk.cjs",
|
||||||
},
|
"build:all": "powershell -NoProfile -ExecutionPolicy Bypass -File scripts/build-all.ps1"
|
||||||
"devDependencies": {
|
},
|
||||||
"@capacitor/cli": "^8.5.2",
|
"devDependencies": {
|
||||||
"electron": "44.5.1",
|
"@capacitor/cli": "^8.5.2",
|
||||||
"electron-builder": "26.17.0",
|
"electron": "44.5.1",
|
||||||
"esbuild": "^0.28.2"
|
"electron-builder": "26.17.0",
|
||||||
},
|
"esbuild": "^0.28.2"
|
||||||
"build": {
|
},
|
||||||
"appId": "studio.daybreak.mail",
|
"build": {
|
||||||
"productName": "ep-mail",
|
"appId": "studio.daybreak.mail",
|
||||||
"asar": true,
|
"productName": "ep-mail",
|
||||||
"files": [
|
"asar": true,
|
||||||
"index.html",
|
"files": [
|
||||||
"platform-bridge.js",
|
"index.html",
|
||||||
"platform-bridge-loader.js",
|
"platform-bridge.js",
|
||||||
"styles.css",
|
"platform-bridge-loader.js",
|
||||||
"branding.css",
|
"styles.css",
|
||||||
"renderer-state.js",
|
"branding.css",
|
||||||
"mail-content-security.js",
|
"renderer-state.js",
|
||||||
"renderer-mail-api.js",
|
"mail-content-security.js",
|
||||||
"app.js",
|
"renderer-mail-api.js",
|
||||||
"mail-ui.js",
|
"app.js",
|
||||||
"productivity.js",
|
"mail-ui.js",
|
||||||
"account-ui.js",
|
"productivity.js",
|
||||||
"dav-ui.js",
|
"account-ui.js",
|
||||||
"shortcuts.js",
|
"dav-ui.js",
|
||||||
"attachments.js",
|
"shortcuts.js",
|
||||||
"pgp-ui.js",
|
"attachments.js",
|
||||||
"pgp-mail-ui.js",
|
"pgp-ui.js",
|
||||||
"icon.svg",
|
"pgp-mail-ui.js",
|
||||||
"icon.ico",
|
"icon.svg",
|
||||||
"logo-ep-daylight.svg",
|
"icon.ico",
|
||||||
"logo-ep-wasteland.svg",
|
"logo-ep-daylight.svg",
|
||||||
"manifest.webmanifest",
|
"logo-ep-wasteland.svg",
|
||||||
"service-worker.js",
|
"manifest.webmanifest",
|
||||||
"snooze-ui.js",
|
"service-worker.js",
|
||||||
"desktop/**/*"
|
"snooze-ui.js",
|
||||||
],
|
"desktop/**/*"
|
||||||
"directories": {
|
],
|
||||||
"output": "release"
|
"directories": {
|
||||||
},
|
"output": "release"
|
||||||
"win": {
|
},
|
||||||
"icon": "icon.ico",
|
"win": {
|
||||||
"target": [
|
"icon": "icon.ico",
|
||||||
"nsis",
|
"target": [
|
||||||
"portable"
|
"nsis",
|
||||||
]
|
"portable"
|
||||||
},
|
]
|
||||||
"nsis": {
|
},
|
||||||
"oneClick": false,
|
"nsis": {
|
||||||
"allowToChangeInstallationDirectory": true,
|
"oneClick": false,
|
||||||
"createDesktopShortcut": true,
|
"allowToChangeInstallationDirectory": true,
|
||||||
"createStartMenuShortcut": true
|
"createDesktopShortcut": true,
|
||||||
},
|
"createStartMenuShortcut": true
|
||||||
"linux": {
|
},
|
||||||
"category": "Office",
|
"linux": {
|
||||||
"syncDesktopName": true,
|
"category": "Office",
|
||||||
"target": [
|
"syncDesktopName": true,
|
||||||
"AppImage",
|
"target": [
|
||||||
"deb"
|
"AppImage",
|
||||||
],
|
"deb"
|
||||||
"maintainer": "Tero Huttunen <tero.huttunen@eternityproject.fi>",
|
],
|
||||||
"synopsis": "A calmer place for mail, people, and plans"
|
"maintainer": "Tero Huttunen <tero.huttunen@eternityproject.fi>",
|
||||||
}
|
"synopsis": "A calmer place for mail, people, and plans"
|
||||||
},
|
}
|
||||||
"allowScripts": {
|
},
|
||||||
"electron@44.5.1": true,
|
"allowScripts": {
|
||||||
"electron-winstaller@5.4.0": true,
|
"electron@44.5.1": true,
|
||||||
"esbuild@0.28.2": true
|
"electron-winstaller@5.4.0": true,
|
||||||
},
|
"esbuild@0.28.2": true
|
||||||
"dependencies": {
|
},
|
||||||
"@capacitor/android": "^8.5.2",
|
"dependencies": {
|
||||||
"@capacitor/core": "^8.5.2",
|
"@capacitor/android": "^8.5.2",
|
||||||
"ical.js": "^2.2.1",
|
"@capacitor/core": "^8.5.2",
|
||||||
"imapflow": "2.2.1",
|
"ical.js": "^2.2.1",
|
||||||
"mailparser": "3.9.33",
|
"imapflow": "2.2.1",
|
||||||
"nodemailer": "10.0.9",
|
"mailparser": "3.9.33",
|
||||||
"openpgp": "^6.3.2",
|
"nodemailer": "10.0.9",
|
||||||
"tsdav": "^2.3.4",
|
"openpgp": "^6.3.2",
|
||||||
"v8-compile-cache": "^2.4.0"
|
"tsdav": "^2.3.4",
|
||||||
}
|
"v8-compile-cache": "^2.4.0"
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -6,193 +6,193 @@ const selectAllPgpMailUi = pgpMailUi.selectAll;
|
|||||||
const toastPgpMailUi = pgpMailUi.toast;
|
const toastPgpMailUi = pgpMailUi.toast;
|
||||||
const escapePgpMailUi = pgpMailUi.escapeHtml;
|
const escapePgpMailUi = pgpMailUi.escapeHtml;
|
||||||
const pgpApi = () => window.daybreakMail?.pgp;
|
const pgpApi = () => window.daybreakMail?.pgp;
|
||||||
|
|
||||||
function pgpAskPassphrase(title, detail) {
|
function pgpAskPassphrase(title, detail) {
|
||||||
return new Promise(resolve => {
|
return new Promise(resolve => {
|
||||||
const overlay = document.createElement('div');
|
const overlay = document.createElement('div');
|
||||||
overlay.className = 'modal-overlay pgp-prompt';
|
overlay.className = 'modal-overlay pgp-prompt';
|
||||||
overlay.innerHTML = `<form class="compose-modal pgp-prompt-box" autocomplete="off"><div class="modal-head"><span></span></div><div class="compose-fields"><p class="account-note"></p><label class="compose-line"><span>Passphrase</span><input type="password" id="pgp-prompt-input" autocomplete="current-password"></label></div><div class="compose-footer"><button type="button" class="discard" data-cancel>Cancel</button><button type="submit" class="send-button">Unlock</button></div></form>`;
|
overlay.innerHTML = `<form class="compose-modal pgp-prompt-box" autocomplete="off"><div class="modal-head"><span></span></div><div class="compose-fields"><p class="account-note"></p><label class="compose-line"><span>Passphrase</span><input type="password" id="pgp-prompt-input" autocomplete="current-password"></label></div><div class="compose-footer"><button type="button" class="discard" data-cancel>Cancel</button><button type="submit" class="send-button">Unlock</button></div></form>`;
|
||||||
overlay.querySelector('.modal-head span').textContent = title;
|
overlay.querySelector('.modal-head span').textContent = title;
|
||||||
overlay.querySelector('.account-note').textContent = detail;
|
overlay.querySelector('.account-note').textContent = detail;
|
||||||
const finish = value => { overlay.remove(); resolve(value); };
|
const finish = value => { overlay.remove(); resolve(value); };
|
||||||
overlay.querySelector('form').onsubmit = event => {
|
overlay.querySelector('form').onsubmit = event => {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
const value = overlay.querySelector('input').value;
|
const value = overlay.querySelector('input').value;
|
||||||
if (value) finish(value);
|
if (value) finish(value);
|
||||||
};
|
};
|
||||||
overlay.querySelector('[data-cancel]').onclick = () => finish(null);
|
overlay.querySelector('[data-cancel]').onclick = () => finish(null);
|
||||||
overlay.addEventListener('keydown', event => { if (event.key === 'Escape') { event.stopPropagation(); finish(null); } });
|
overlay.addEventListener('keydown', event => { if (event.key === 'Escape') { event.stopPropagation(); finish(null); } });
|
||||||
document.body.append(overlay);
|
document.body.append(overlay);
|
||||||
overlay.querySelector('input').focus();
|
overlay.querySelector('input').focus();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function pgpFormatFingerprint(value) {
|
function pgpFormatFingerprint(value) {
|
||||||
return String(value || '').match(/.{1,4}/g)?.join(' ') || '';
|
return String(value || '').match(/.{1,4}/g)?.join(' ') || '';
|
||||||
}
|
}
|
||||||
|
|
||||||
function pgpSignatureHtml(signatures, encrypted) {
|
function pgpSignatureHtml(signatures, encrypted) {
|
||||||
const items = Array.isArray(signatures) ? signatures : [];
|
const items = Array.isArray(signatures) ? signatures : [];
|
||||||
const lock = encrypted ? '🔒 Encrypted. ' : '';
|
const lock = encrypted ? '🔒 Encrypted. ' : '';
|
||||||
if (!items.length) {
|
if (!items.length) {
|
||||||
return encrypted ? `<section class="pgp-status pgp-warn" role="status"><strong>${lock}Not signed</strong><span>The sender is not authenticated: anyone with your public key could have written this.</span></section>` : '';
|
return encrypted ? `<section class="pgp-status pgp-warn" role="status"><strong>${lock}Not signed</strong><span>The sender is not authenticated: anyone with your public key could have written this.</span></section>` : '';
|
||||||
}
|
}
|
||||||
return items.map(signature => {
|
return items.map(signature => {
|
||||||
const trust = signature.trust === 'verified' ? 'verified key' : signature.trust === 'trusted' ? 'trusted key' : 'key not verified yet';
|
const trust = signature.trust === 'verified' ? 'verified key' : signature.trust === 'trusted' ? 'trusted key' : 'key not verified yet';
|
||||||
const notes = [];
|
const notes = [];
|
||||||
if (signature.keyChanged) notes.push('The sender previously used a different key. Confirm the change with them before trusting this message.');
|
if (signature.keyChanged) notes.push('The sender previously used a different key. Confirm the change with them before trusting this message.');
|
||||||
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 ${escapePgpMailUi(signature.email || 'a known key')}</strong><span>${escapePgpMailUi(trust)} · ${escapePgpMailUi(pgpFormatFingerprint(signature.fingerprint))}</span>${notes.map(note => `<small>${escapePgpMailUi(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 ${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-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('');
|
||||||
}
|
}
|
||||||
|
|
||||||
async function pgpAddAttachedKey(key) {
|
async function pgpAddAttachedKey(key) {
|
||||||
const emails = key.emails.join(', ') || 'unknown address';
|
const emails = key.emails.join(', ') || 'unknown address';
|
||||||
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' });
|
||||||
toastPgpMailUi(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) {
|
||||||
toastPgpMailUi(error.message || 'Could not add the key');
|
toastPgpMailUi(error.message || 'Could not add the key');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function pgpRenderReaderState(message) {
|
function pgpRenderReaderState(message) {
|
||||||
const reader = selectPgpMailUi('#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());
|
||||||
let html = '';
|
let html = '';
|
||||||
if (message.encrypted && !message.pgpDecrypted) {
|
if (message.encrypted && !message.pgpDecrypted) {
|
||||||
html = `<section class="pgp-banner" role="status"><strong>🔒 This message is encrypted</strong><span id="pgp-banner-text">Unlock it with your key passphrase to read it.</span><button type="button" class="send-button" id="pgp-unlock">Unlock</button></section>`;
|
html = `<section class="pgp-banner" role="status"><strong>🔒 This message is encrypted</strong><span id="pgp-banner-text">Unlock it with your key passphrase to read it.</span><button type="button" class="send-button" id="pgp-unlock">Unlock</button></section>`;
|
||||||
} else if (message.encrypted) {
|
} else if (message.encrypted) {
|
||||||
html = pgpSignatureHtml(message.pgpResult?.signatures, true);
|
html = pgpSignatureHtml(message.pgpResult?.signatures, true);
|
||||||
} else if (message.pgpSignatures) {
|
} else if (message.pgpSignatures) {
|
||||||
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>${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(''));
|
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 = selectPgpMailUi('#pgp-unlock');
|
const unlock = selectPgpMailUi('#pgp-unlock');
|
||||||
if (unlock) unlock.onclick = () => pgpUnlockMessage(message, true);
|
if (unlock) unlock.onclick = () => pgpUnlockMessage(message, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function pgpUnlockMessage(message, interactive) {
|
async function pgpUnlockMessage(message, interactive) {
|
||||||
let passphrase = null;
|
let passphrase = null;
|
||||||
for (let attempt = 0; attempt < 3; attempt += 1) {
|
for (let attempt = 0; attempt < 3; attempt += 1) {
|
||||||
let result;
|
let result;
|
||||||
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) {
|
||||||
toastPgpMailUi(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, html: result.html, 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 (pgpMailUi.state.activeMessage === message.id) pgpMailUi.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') {
|
||||||
if (!interactive) { pgpRenderReaderState(message); return; }
|
if (!interactive) { pgpRenderReaderState(message); return; }
|
||||||
passphrase = await pgpAskPassphrase('Unlock encrypted message', result.code === 'BAD_PASSPHRASE' ? 'That passphrase was incorrect. Try again.' : `Enter the passphrase for ${result.email || 'your key'}.`);
|
passphrase = await pgpAskPassphrase('Unlock encrypted message', result.code === 'BAD_PASSPHRASE' ? 'That passphrase was incorrect. Try again.' : `Enter the passphrase for ${result.email || 'your key'}.`);
|
||||||
if (passphrase === null) return;
|
if (passphrase === null) return;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
const text = selectPgpMailUi('#pgp-banner-text');
|
const text = selectPgpMailUi('#pgp-banner-text');
|
||||||
if (text) text.textContent = result.message;
|
if (text) text.textContent = result.message;
|
||||||
else toastPgpMailUi(result.message);
|
else toastPgpMailUi(result.message);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pgpMailUi.wrapOpenMessage(baseOpenMessage => function (id) {
|
pgpMailUi.wrapOpenMessage(baseOpenMessage => function (id) {
|
||||||
baseOpenMessage(id);
|
baseOpenMessage(id);
|
||||||
const message = pgpMailUi.state.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.
|
||||||
pgpMailUi.wrapShowCompose(baseShowCompose => function (reply, forward = false) {
|
pgpMailUi.wrapShowCompose(baseShowCompose => function (reply, forward = false) {
|
||||||
baseShowCompose(reply, forward);
|
baseShowCompose(reply, forward);
|
||||||
const footer = selectPgpMailUi('#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 = selectPgpMailUi('#pgp-encrypt');
|
const encrypt = selectPgpMailUi('#pgp-encrypt');
|
||||||
const sign = selectPgpMailUi('#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 = selectPgpMailUi('#compose-to')?.value || '';
|
const to = selectPgpMailUi('#compose-to')?.value || '';
|
||||||
const cc = selectPgpMailUi('#compose-cc')?.value || '';
|
const cc = selectPgpMailUi('#compose-cc')?.value || '';
|
||||||
const hint = selectPgpMailUi('#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 (!selectPgpMailUi('#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';
|
||||||
if (!touched && !encrypt.checked) encrypt.checked = true;
|
if (!touched && !encrypt.checked) encrypt.checked = true;
|
||||||
}
|
}
|
||||||
} 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 => selectPgpMailUi(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.
|
||||||
async function prepareSend(to, cc) {
|
async function prepareSend(to, cc) {
|
||||||
if (!pgpApi()) return null;
|
if (!pgpApi()) return null;
|
||||||
let encrypt = Boolean(selectPgpMailUi('#pgp-encrypt')?.checked);
|
let encrypt = Boolean(selectPgpMailUi('#pgp-encrypt')?.checked);
|
||||||
const sign = Boolean(selectPgpMailUi('#pgp-sign')?.checked);
|
const sign = Boolean(selectPgpMailUi('#pgp-sign')?.checked);
|
||||||
if (!encrypt && !sign && selectPgpMailUi('#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 && selectPgpMailUi('#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;
|
||||||
}
|
}
|
||||||
if (!encrypt && !sign) return null;
|
if (!encrypt && !sign) return null;
|
||||||
if (encrypt && status.missing.length) {
|
if (encrypt && status.missing.length) {
|
||||||
const sendPlain = confirm(`No public key for ${status.missing.join(', ')}.\n\nThe message cannot be encrypted for everyone. Send it WITHOUT encryption?`);
|
const sendPlain = confirm(`No public key for ${status.missing.join(', ')}.\n\nThe message cannot be encrypted for everyone. Send it WITHOUT encryption?`);
|
||||||
if (!sendPlain) return false;
|
if (!sendPlain) return false;
|
||||||
encrypt = false;
|
encrypt = false;
|
||||||
if (!sign) return null;
|
if (!sign) return null;
|
||||||
}
|
}
|
||||||
let passphrase = null;
|
let passphrase = null;
|
||||||
if (sign) {
|
if (sign) {
|
||||||
if (!status.signer) { toastPgpMailUi('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 };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,418 +6,418 @@ const selectAllPgpKeyUi = pgpKeyMailUi.selectAll;
|
|||||||
const escapePgpKeyUi = pgpKeyMailUi.escapeHtml;
|
const escapePgpKeyUi = pgpKeyMailUi.escapeHtml;
|
||||||
const toastPgpKeyUi = pgpKeyMailUi.toast;
|
const toastPgpKeyUi = pgpKeyMailUi.toast;
|
||||||
function pgpAvailable() { return Boolean(window.daybreakMail?.pgp); }
|
function pgpAvailable() { return Boolean(window.daybreakMail?.pgp); }
|
||||||
|
|
||||||
function openEncryptionKeys() {
|
function openEncryptionKeys() {
|
||||||
const root = selectPgpKeyUi('#modal-root');
|
const root = selectPgpKeyUi('#modal-root');
|
||||||
const account = window.epMailFeatures.mail.connectedAccount || {};
|
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>
|
<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>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>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>
|
<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>
|
<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>
|
<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>
|
<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>
|
<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>
|
<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 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>
|
<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>
|
<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>
|
<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>
|
<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>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>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>
|
<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>
|
<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="${escapePgpKeyUi(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="${escapePgpKeyUi(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>
|
||||||
</div></div></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 status = message => { selectPgpKeyUi('#pgp-status').textContent = message; };
|
const status = message => { selectPgpKeyUi('#pgp-status').textContent = message; };
|
||||||
const passphraseField = () => selectPgpKeyUi('#pgp-passphrase');
|
const passphraseField = () => selectPgpKeyUi('#pgp-passphrase');
|
||||||
let keyServers = [];
|
let keyServers = [];
|
||||||
const selectedPublishServer = () => keyServers.find(server => server.id === selectPgpKeyUi('#pgp-publish-server').value && server.enabled);
|
const selectedPublishServer = () => keyServers.find(server => server.id === selectPgpKeyUi('#pgp-publish-server').value && server.enabled);
|
||||||
const updatePublishButtons = () => {
|
const updatePublishButtons = () => {
|
||||||
const server = selectedPublishServer();
|
const server = selectedPublishServer();
|
||||||
selectAllPgpKeyUi('.pgp-publish').forEach(button => {
|
selectAllPgpKeyUi('.pgp-publish').forEach(button => {
|
||||||
button.disabled = !server;
|
button.disabled = !server;
|
||||||
button.textContent = server ? `Publish to ${server.name}…` : 'Enable a server to publish…';
|
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(); }
|
||||||
return value;
|
return value;
|
||||||
};
|
};
|
||||||
|
|
||||||
async function render() {
|
async function render() {
|
||||||
const list = selectPgpKeyUi('#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();
|
||||||
if (!keys.length) { list.textContent = 'No keys yet.'; return; }
|
if (!keys.length) { list.textContent = 'No keys yet.'; return; }
|
||||||
keys.forEach(key => {
|
keys.forEach(key => {
|
||||||
const row = document.createElement('div');
|
const row = document.createElement('div');
|
||||||
row.className = 'attachment-row';
|
row.className = 'attachment-row';
|
||||||
const info = document.createElement('div');
|
const info = document.createElement('div');
|
||||||
info.className = 'attachment-row-info';
|
info.className = 'attachment-row-info';
|
||||||
const title = document.createElement('strong');
|
const title = document.createElement('strong');
|
||||||
title.textContent = key.email || 'OpenPGP key';
|
title.textContent = key.email || 'OpenPGP key';
|
||||||
const meta = document.createElement('small');
|
const meta = document.createElement('small');
|
||||||
meta.textContent = `${key.name ? key.name + ' · ' : ''}${key.algorithm} · ${new Date(key.createdAt).toLocaleDateString()}`;
|
meta.textContent = `${key.name ? key.name + ' · ' : ''}${key.algorithm} · ${new Date(key.createdAt).toLocaleDateString()}`;
|
||||||
const fingerprint = document.createElement('small');
|
const fingerprint = document.createElement('small');
|
||||||
fingerprint.textContent = `Fingerprint: ${key.fingerprint.match(/.{1,4}/g).join(' ')}`;
|
fingerprint.textContent = `Fingerprint: ${key.fingerprint.match(/.{1,4}/g).join(' ')}`;
|
||||||
info.append(title, meta, fingerprint);
|
info.append(title, meta, fingerprint);
|
||||||
row.append(info);
|
row.append(info);
|
||||||
const actions = [
|
const actions = [
|
||||||
['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');
|
const changePassphrase = document.createElement('button');
|
||||||
changePassphrase.className = 'discard';
|
changePassphrase.className = 'discard';
|
||||||
changePassphrase.textContent = 'Change passphrase…';
|
changePassphrase.textContent = 'Change passphrase…';
|
||||||
changePassphrase.onclick = async () => {
|
changePassphrase.onclick = async () => {
|
||||||
const currentPassphrase = selectPgpKeyUi('#pgp-change-current-passphrase').value;
|
const currentPassphrase = selectPgpKeyUi('#pgp-change-current-passphrase').value;
|
||||||
if (!currentPassphrase) {
|
if (!currentPassphrase) {
|
||||||
status('Enter the current passphrase for this key.');
|
status('Enter the current passphrase for this key.');
|
||||||
selectPgpKeyUi('#pgp-change-current-passphrase').focus();
|
selectPgpKeyUi('#pgp-change-current-passphrase').focus();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const newPassphrase = selectPgpKeyUi('#pgp-new-passphrase').value;
|
const newPassphrase = selectPgpKeyUi('#pgp-new-passphrase').value;
|
||||||
if (newPassphrase.length < 8) {
|
if (newPassphrase.length < 8) {
|
||||||
status('Use a new passphrase of at least 8 characters.');
|
status('Use a new passphrase of at least 8 characters.');
|
||||||
selectPgpKeyUi('#pgp-new-passphrase').focus();
|
selectPgpKeyUi('#pgp-new-passphrase').focus();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (newPassphrase !== selectPgpKeyUi('#pgp-confirm-passphrase').value) {
|
if (newPassphrase !== selectPgpKeyUi('#pgp-confirm-passphrase').value) {
|
||||||
status('The new passphrases do not match.');
|
status('The new passphrases do not match.');
|
||||||
selectPgpKeyUi('#pgp-confirm-passphrase').focus();
|
selectPgpKeyUi('#pgp-confirm-passphrase').focus();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
changePassphrase.disabled = true;
|
changePassphrase.disabled = true;
|
||||||
try {
|
try {
|
||||||
await window.daybreakMail.pgp.changePassphrase({
|
await window.daybreakMail.pgp.changePassphrase({
|
||||||
fingerprint: key.fingerprint,
|
fingerprint: key.fingerprint,
|
||||||
currentPassphrase,
|
currentPassphrase,
|
||||||
newPassphrase
|
newPassphrase
|
||||||
});
|
});
|
||||||
selectPgpKeyUi('#pgp-change-current-passphrase').value = '';
|
selectPgpKeyUi('#pgp-change-current-passphrase').value = '';
|
||||||
status(`Passphrase changed for ${key.email || key.fingerprint}.`);
|
status(`Passphrase changed for ${key.email || key.fingerprint}.`);
|
||||||
} catch (error) { status(error.message || 'Could not change the key passphrase.'); }
|
} catch (error) { status(error.message || 'Could not change the key passphrase.'); }
|
||||||
finally {
|
finally {
|
||||||
selectPgpKeyUi('#pgp-new-passphrase').value = '';
|
selectPgpKeyUi('#pgp-new-passphrase').value = '';
|
||||||
selectPgpKeyUi('#pgp-confirm-passphrase').value = '';
|
selectPgpKeyUi('#pgp-confirm-passphrase').value = '';
|
||||||
changePassphrase.disabled = false;
|
changePassphrase.disabled = false;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
row.append(changePassphrase);
|
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 };
|
||||||
await window.daybreakMail.pgp.remove(key.fingerprint, needPassphrase());
|
await window.daybreakMail.pgp.remove(key.fingerprint, needPassphrase());
|
||||||
await render();
|
await render();
|
||||||
return { deleted: true };
|
return { deleted: true };
|
||||||
}, true]);
|
}, true]);
|
||||||
actions.forEach(([label, run, secret]) => {
|
actions.forEach(([label, run, secret]) => {
|
||||||
const button = document.createElement('button');
|
const button = document.createElement('button');
|
||||||
button.className = 'discard';
|
button.className = 'discard';
|
||||||
button.textContent = label;
|
button.textContent = label;
|
||||||
button.onclick = async () => {
|
button.onclick = async () => {
|
||||||
if (secret && !passphraseField().value) { needPassphrase(); return; }
|
if (secret && !passphraseField().value) { needPassphrase(); return; }
|
||||||
try {
|
try {
|
||||||
const result = await run();
|
const result = await run();
|
||||||
status(result?.saved ? 'File saved.' : result?.deleted ? 'Key deleted.' : '');
|
status(result?.saved ? 'File saved.' : result?.deleted ? 'Key deleted.' : '');
|
||||||
} catch (error) { status(error.message || 'That action failed.'); }
|
} catch (error) { status(error.message || 'That action failed.'); }
|
||||||
};
|
};
|
||||||
row.append(button);
|
row.append(button);
|
||||||
});
|
});
|
||||||
const publish = document.createElement('button');
|
const publish = document.createElement('button');
|
||||||
publish.className = 'discard pgp-publish';
|
publish.className = 'discard pgp-publish';
|
||||||
publish.onclick = async () => {
|
publish.onclick = async () => {
|
||||||
const server = selectedPublishServer();
|
const server = selectedPublishServer();
|
||||||
if (!server) { status('Enable a key server and select it as the publication target first.'); return; }
|
if (!server) { status('Enable a key server and select it as the publication target first.'); return; }
|
||||||
publish.disabled = true;
|
publish.disabled = true;
|
||||||
try {
|
try {
|
||||||
const result = await window.daybreakMail.pgp.publishKey({ fingerprint: key.fingerprint, serverId: server.id });
|
const result = await window.daybreakMail.pgp.publishKey({ fingerprint: key.fingerprint, serverId: server.id });
|
||||||
if (result.canceled) return;
|
if (result.canceled) return;
|
||||||
if (result.warning) status(result.warning);
|
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 === '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 === '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 === '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 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());
|
else status(`${server.name} accepted the key. ${result.message || ''}`.trim());
|
||||||
} catch (error) { status(error.message || 'Could not publish the public key.'); }
|
} catch (error) { status(error.message || 'Could not publish the public key.'); }
|
||||||
finally { updatePublishButtons(); }
|
finally { updatePublishButtons(); }
|
||||||
};
|
};
|
||||||
row.append(publish);
|
row.append(publish);
|
||||||
list.append(row);
|
list.append(row);
|
||||||
});
|
});
|
||||||
updatePublishButtons();
|
updatePublishButtons();
|
||||||
}
|
}
|
||||||
|
|
||||||
selectPgpKeyUi('#pgp-generate').onclick = async () => {
|
selectPgpKeyUi('#pgp-generate').onclick = async () => {
|
||||||
const button = selectPgpKeyUi('#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: selectPgpKeyUi('#pgp-name').value, email: selectPgpKeyUi('#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;
|
||||||
};
|
};
|
||||||
selectPgpKeyUi('#pgp-import').onclick = async () => {
|
selectPgpKeyUi('#pgp-import').onclick = async () => {
|
||||||
const passphrase = needPassphrase();
|
const passphrase = needPassphrase();
|
||||||
if (!passphrase) return;
|
if (!passphrase) return;
|
||||||
try {
|
try {
|
||||||
const result = await window.daybreakMail.pgp.importKey({ passphrase, accountId: account.id || null });
|
const result = await window.daybreakMail.pgp.importKey({ passphrase, accountId: account.id || null });
|
||||||
status(result.canceled ? '' : 'Key imported.');
|
status(result.canceled ? '' : 'Key imported.');
|
||||||
await render();
|
await render();
|
||||||
} 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 = selectPgpKeyUi('#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();
|
||||||
if (!contacts.length) { list.textContent = 'No contact keys yet. Import a public key, or add one from a received message.'; return; }
|
if (!contacts.length) { list.textContent = 'No contact keys yet. Import a public key, or add one from a received message.'; return; }
|
||||||
contacts.forEach(contact => {
|
contacts.forEach(contact => {
|
||||||
const row = document.createElement('div');
|
const row = document.createElement('div');
|
||||||
row.className = 'attachment-row';
|
row.className = 'attachment-row';
|
||||||
const info = document.createElement('div');
|
const info = document.createElement('div');
|
||||||
info.className = 'attachment-row-info';
|
info.className = 'attachment-row-info';
|
||||||
const title = document.createElement('strong');
|
const title = document.createElement('strong');
|
||||||
title.textContent = contact.emails.join(', ') || contact.name || 'Public key';
|
title.textContent = contact.emails.join(', ') || contact.name || 'Public key';
|
||||||
const meta = document.createElement('small');
|
const meta = document.createElement('small');
|
||||||
meta.textContent = `${contact.name ? contact.name + ' · ' : ''}added ${new Date(contact.addedAt).toLocaleDateString()} · from ${contact.source}`;
|
meta.textContent = `${contact.name ? contact.name + ' · ' : ''}added ${new Date(contact.addedAt).toLocaleDateString()} · from ${contact.source}`;
|
||||||
const fingerprint = document.createElement('small');
|
const fingerprint = document.createElement('small');
|
||||||
fingerprint.textContent = `Fingerprint: ${contact.fingerprint.match(/.{1,4}/g).join(' ')}`;
|
fingerprint.textContent = `Fingerprint: ${contact.fingerprint.match(/.{1,4}/g).join(' ')}`;
|
||||||
info.append(title, meta, fingerprint);
|
info.append(title, meta, fingerprint);
|
||||||
const trust = document.createElement('select');
|
const trust = document.createElement('select');
|
||||||
trust.className = 'pgp-trust';
|
trust.className = 'pgp-trust';
|
||||||
trust.setAttribute('aria-label', 'Key trust');
|
trust.setAttribute('aria-label', 'Key trust');
|
||||||
[['unknown', 'Not verified'], ['trusted', 'Trusted'], ['verified', 'Verified (fingerprint checked)']].forEach(([value, label]) => {
|
[['unknown', 'Not verified'], ['trusted', 'Trusted'], ['verified', 'Verified (fingerprint checked)']].forEach(([value, label]) => {
|
||||||
const option = document.createElement('option');
|
const option = document.createElement('option');
|
||||||
option.value = value; option.textContent = label; option.selected = contact.trust === value;
|
option.value = value; option.textContent = label; option.selected = contact.trust === value;
|
||||||
trust.append(option);
|
trust.append(option);
|
||||||
});
|
});
|
||||||
trust.onchange = async () => {
|
trust.onchange = async () => {
|
||||||
if (trust.value === 'verified' && !confirm(`Mark this key as verified only if you compared this fingerprint with its owner through another channel:\n\n${contact.fingerprint.match(/.{1,4}/g).join(' ')}`)) {
|
if (trust.value === 'verified' && !confirm(`Mark this key as verified only if you compared this fingerprint with its owner through another channel:\n\n${contact.fingerprint.match(/.{1,4}/g).join(' ')}`)) {
|
||||||
trust.value = contact.trust;
|
trust.value = contact.trust;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
try { await window.daybreakMail.pgp.setTrust(contact.fingerprint, trust.value); contact.trust = trust.value; status('Trust updated.'); }
|
try { await window.daybreakMail.pgp.setTrust(contact.fingerprint, trust.value); contact.trust = trust.value; status('Trust updated.'); }
|
||||||
catch (error) { trust.value = contact.trust; status(error.message || 'Could not update trust.'); }
|
catch (error) { trust.value = contact.trust; status(error.message || 'Could not update trust.'); }
|
||||||
};
|
};
|
||||||
const actions = [
|
const actions = [
|
||||||
['Export', () => window.daybreakMail.pgp.exportContact(contact.fingerprint)],
|
['Export', () => window.daybreakMail.pgp.exportContact(contact.fingerprint)],
|
||||||
['Remove', async () => {
|
['Remove', async () => {
|
||||||
if (!confirm('Remove this contact key? You will no longer be able to encrypt to it.')) return { canceled: true };
|
if (!confirm('Remove this contact key? You will no longer be able to encrypt to it.')) return { canceled: true };
|
||||||
await window.daybreakMail.pgp.removeContact(contact.fingerprint);
|
await window.daybreakMail.pgp.removeContact(contact.fingerprint);
|
||||||
await renderContacts();
|
await renderContacts();
|
||||||
return { deleted: true };
|
return { deleted: true };
|
||||||
}]
|
}]
|
||||||
];
|
];
|
||||||
row.append(info, trust);
|
row.append(info, trust);
|
||||||
actions.forEach(([label, run]) => {
|
actions.forEach(([label, run]) => {
|
||||||
const button = document.createElement('button');
|
const button = document.createElement('button');
|
||||||
button.className = 'discard';
|
button.className = 'discard';
|
||||||
button.textContent = label;
|
button.textContent = label;
|
||||||
button.onclick = async () => {
|
button.onclick = async () => {
|
||||||
try { const result = await run(); status(result?.saved ? 'File saved.' : result?.deleted ? 'Contact key removed.' : ''); }
|
try { const result = await run(); status(result?.saved ? 'File saved.' : result?.deleted ? 'Contact key removed.' : ''); }
|
||||||
catch (error) { status(error.message || 'That action failed.'); }
|
catch (error) { status(error.message || 'That action failed.'); }
|
||||||
};
|
};
|
||||||
row.append(button);
|
row.append(button);
|
||||||
});
|
});
|
||||||
list.append(row);
|
list.append(row);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
selectPgpKeyUi('#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.'); }
|
||||||
};
|
};
|
||||||
async function renderKeyServers() {
|
async function renderKeyServers() {
|
||||||
const list = selectPgpKeyUi('#pgp-server-list');
|
const list = selectPgpKeyUi('#pgp-server-list');
|
||||||
const selector = selectPgpKeyUi('#pgp-publish-server');
|
const selector = selectPgpKeyUi('#pgp-publish-server');
|
||||||
const selectedId = selector.value;
|
const selectedId = selector.value;
|
||||||
try { keyServers = await window.daybreakMail.pgp.keyServers(); }
|
try { keyServers = await window.daybreakMail.pgp.keyServers(); }
|
||||||
catch (error) { list.textContent = error.message || 'Could not load key servers.'; return; }
|
catch (error) { list.textContent = error.message || 'Could not load key servers.'; return; }
|
||||||
selector.replaceChildren();
|
selector.replaceChildren();
|
||||||
const enabledServers = keyServers.filter(server => server.enabled);
|
const enabledServers = keyServers.filter(server => server.enabled);
|
||||||
if (!enabledServers.length) {
|
if (!enabledServers.length) {
|
||||||
const option = document.createElement('option');
|
const option = document.createElement('option');
|
||||||
option.value = '';
|
option.value = '';
|
||||||
option.textContent = 'No enabled servers';
|
option.textContent = 'No enabled servers';
|
||||||
selector.append(option);
|
selector.append(option);
|
||||||
} else enabledServers.forEach(server => {
|
} else enabledServers.forEach(server => {
|
||||||
const option = document.createElement('option');
|
const option = document.createElement('option');
|
||||||
option.value = server.id;
|
option.value = server.id;
|
||||||
option.textContent = `${server.name} (${server.protocol.toUpperCase()})`;
|
option.textContent = `${server.name} (${server.protocol.toUpperCase()})`;
|
||||||
option.selected = server.id === selectedId;
|
option.selected = server.id === selectedId;
|
||||||
selector.append(option);
|
selector.append(option);
|
||||||
});
|
});
|
||||||
if (selectedId && !enabledServers.some(server => server.id === selectedId)) selector.selectedIndex = 0;
|
if (selectedId && !enabledServers.some(server => server.id === selectedId)) selector.selectedIndex = 0;
|
||||||
selector.onchange = updatePublishButtons;
|
selector.onchange = updatePublishButtons;
|
||||||
list.replaceChildren();
|
list.replaceChildren();
|
||||||
keyServers.forEach(server => {
|
keyServers.forEach(server => {
|
||||||
const row = document.createElement('div');
|
const row = document.createElement('div');
|
||||||
row.className = 'attachment-row';
|
row.className = 'attachment-row';
|
||||||
const info = document.createElement('div');
|
const info = document.createElement('div');
|
||||||
info.className = 'attachment-row-info';
|
info.className = 'attachment-row-info';
|
||||||
const title = document.createElement('strong');
|
const title = document.createElement('strong');
|
||||||
title.textContent = server.name;
|
title.textContent = server.name;
|
||||||
const details = document.createElement('small');
|
const details = document.createElement('small');
|
||||||
details.textContent = `${server.protocol.toUpperCase()} · ${server.url}${server.builtin ? ' · built in' : ' · custom'}`;
|
details.textContent = `${server.protocol.toUpperCase()} · ${server.url}${server.builtin ? ' · built in' : ' · custom'}`;
|
||||||
info.append(title, details);
|
info.append(title, details);
|
||||||
const enabledLabel = document.createElement('label');
|
const enabledLabel = document.createElement('label');
|
||||||
enabledLabel.className = 'compose-line';
|
enabledLabel.className = 'compose-line';
|
||||||
const enabledText = document.createElement('span');
|
const enabledText = document.createElement('span');
|
||||||
enabledText.textContent = 'Use for lookup and publishing';
|
enabledText.textContent = 'Use for lookup and publishing';
|
||||||
const enabled = document.createElement('input');
|
const enabled = document.createElement('input');
|
||||||
enabled.type = 'checkbox';
|
enabled.type = 'checkbox';
|
||||||
enabled.checked = server.enabled;
|
enabled.checked = server.enabled;
|
||||||
enabled.setAttribute('aria-label', `${server.name} enabled`);
|
enabled.setAttribute('aria-label', `${server.name} enabled`);
|
||||||
enabled.onchange = async () => {
|
enabled.onchange = async () => {
|
||||||
enabled.disabled = true;
|
enabled.disabled = true;
|
||||||
try {
|
try {
|
||||||
await window.daybreakMail.pgp.setKeyServerEnabled(server.id, enabled.checked);
|
await window.daybreakMail.pgp.setKeyServerEnabled(server.id, enabled.checked);
|
||||||
await renderKeyServers();
|
await renderKeyServers();
|
||||||
status(`${server.name} ${enabled.checked ? 'enabled' : 'disabled'}.`);
|
status(`${server.name} ${enabled.checked ? 'enabled' : 'disabled'}.`);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
enabled.checked = server.enabled;
|
enabled.checked = server.enabled;
|
||||||
status(error.message || `Could not update ${server.name}.`);
|
status(error.message || `Could not update ${server.name}.`);
|
||||||
} finally { enabled.disabled = false; }
|
} finally { enabled.disabled = false; }
|
||||||
};
|
};
|
||||||
enabledLabel.append(enabledText, enabled);
|
enabledLabel.append(enabledText, enabled);
|
||||||
row.append(info, enabledLabel);
|
row.append(info, enabledLabel);
|
||||||
if (!server.builtin) {
|
if (!server.builtin) {
|
||||||
const remove = document.createElement('button');
|
const remove = document.createElement('button');
|
||||||
remove.className = 'discard';
|
remove.className = 'discard';
|
||||||
remove.textContent = 'Remove';
|
remove.textContent = 'Remove';
|
||||||
remove.onclick = async () => {
|
remove.onclick = async () => {
|
||||||
try {
|
try {
|
||||||
await window.daybreakMail.pgp.removeKeyServer(server.id);
|
await window.daybreakMail.pgp.removeKeyServer(server.id);
|
||||||
await renderKeyServers();
|
await renderKeyServers();
|
||||||
status('Custom key server removed.');
|
status('Custom key server removed.');
|
||||||
} catch (error) { status(error.message || 'Could not remove the key server.'); }
|
} catch (error) { status(error.message || 'Could not remove the key server.'); }
|
||||||
};
|
};
|
||||||
row.append(remove);
|
row.append(remove);
|
||||||
}
|
}
|
||||||
list.append(row);
|
list.append(row);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
selectPgpKeyUi('#pgp-find-key').onclick = async () => {
|
selectPgpKeyUi('#pgp-find-key').onclick = async () => {
|
||||||
const button = selectPgpKeyUi('#pgp-find-key');
|
const button = selectPgpKeyUi('#pgp-find-key');
|
||||||
const results = selectPgpKeyUi('#pgp-found-keys');
|
const results = selectPgpKeyUi('#pgp-found-keys');
|
||||||
button.disabled = true;
|
button.disabled = true;
|
||||||
results.textContent = 'Searching…';
|
results.textContent = 'Searching…';
|
||||||
try {
|
try {
|
||||||
const found = await window.daybreakMail.pgp.findKey({
|
const found = await window.daybreakMail.pgp.findKey({
|
||||||
email: selectPgpKeyUi('#pgp-search-email').value
|
email: selectPgpKeyUi('#pgp-search-email').value
|
||||||
});
|
});
|
||||||
results.replaceChildren();
|
results.replaceChildren();
|
||||||
found.keys.forEach(key => {
|
found.keys.forEach(key => {
|
||||||
const row = document.createElement('div');
|
const row = document.createElement('div');
|
||||||
row.className = 'attachment-row';
|
row.className = 'attachment-row';
|
||||||
const info = document.createElement('div');
|
const info = document.createElement('div');
|
||||||
info.className = 'attachment-row-info';
|
info.className = 'attachment-row-info';
|
||||||
const title = document.createElement('strong');
|
const title = document.createElement('strong');
|
||||||
title.textContent = key.emails.join(', ') || key.name || 'Public key';
|
title.textContent = key.emails.join(', ') || key.name || 'Public key';
|
||||||
const meta = document.createElement('small');
|
const meta = document.createElement('small');
|
||||||
meta.textContent = `Found on ${key.sources.join(', ')} · not verified`;
|
meta.textContent = `Found on ${key.sources.join(', ')} · not verified`;
|
||||||
const fingerprint = document.createElement('small');
|
const fingerprint = document.createElement('small');
|
||||||
fingerprint.textContent = `Fingerprint: ${key.fingerprint.match(/.{1,4}/g).join(' ')}`;
|
fingerprint.textContent = `Fingerprint: ${key.fingerprint.match(/.{1,4}/g).join(' ')}`;
|
||||||
info.append(title, meta, fingerprint);
|
info.append(title, meta, fingerprint);
|
||||||
const add = document.createElement('button');
|
const add = document.createElement('button');
|
||||||
add.className = 'discard';
|
add.className = 'discard';
|
||||||
add.textContent = 'Add to contacts…';
|
add.textContent = 'Add to contacts…';
|
||||||
add.onclick = async () => {
|
add.onclick = async () => {
|
||||||
add.disabled = true;
|
add.disabled = true;
|
||||||
try {
|
try {
|
||||||
const result = await window.daybreakMail.pgp.addContact({ armoredKey: key.armoredKey, source: 'keyserver' });
|
const result = await window.daybreakMail.pgp.addContact({ armoredKey: key.armoredKey, source: 'keyserver' });
|
||||||
if (result.canceled) return;
|
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.');
|
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();
|
await renderContacts();
|
||||||
row.remove();
|
row.remove();
|
||||||
} catch (error) { status(error.message || 'Could not add the public key.'); }
|
} catch (error) { status(error.message || 'Could not add the public key.'); }
|
||||||
finally { add.disabled = false; }
|
finally { add.disabled = false; }
|
||||||
};
|
};
|
||||||
row.append(info, add);
|
row.append(info, add);
|
||||||
results.append(row);
|
results.append(row);
|
||||||
});
|
});
|
||||||
found.errors.forEach(error => {
|
found.errors.forEach(error => {
|
||||||
const warning = document.createElement('small');
|
const warning = document.createElement('small');
|
||||||
warning.textContent = `${error.name}: ${error.message}`;
|
warning.textContent = `${error.name}: ${error.message}`;
|
||||||
results.append(warning);
|
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 && !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.` : ''}`);
|
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 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).`);
|
else status(`No matching key found across ${found.searchedServers.length} enabled server(s).`);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
results.textContent = '';
|
results.textContent = '';
|
||||||
status(error.message || 'Could not search the key server.');
|
status(error.message || 'Could not search the key server.');
|
||||||
} finally { button.disabled = false; }
|
} finally { button.disabled = false; }
|
||||||
};
|
};
|
||||||
selectPgpKeyUi('#pgp-add-server').onclick = async () => {
|
selectPgpKeyUi('#pgp-add-server').onclick = async () => {
|
||||||
const button = selectPgpKeyUi('#pgp-add-server');
|
const button = selectPgpKeyUi('#pgp-add-server');
|
||||||
button.disabled = true;
|
button.disabled = true;
|
||||||
try {
|
try {
|
||||||
const result = await window.daybreakMail.pgp.addKeyServer({
|
const result = await window.daybreakMail.pgp.addKeyServer({
|
||||||
name: selectPgpKeyUi('#pgp-server-name').value,
|
name: selectPgpKeyUi('#pgp-server-name').value,
|
||||||
url: selectPgpKeyUi('#pgp-server-url').value,
|
url: selectPgpKeyUi('#pgp-server-url').value,
|
||||||
protocol: selectPgpKeyUi('#pgp-server-protocol').value
|
protocol: selectPgpKeyUi('#pgp-server-protocol').value
|
||||||
});
|
});
|
||||||
if (result.canceled) return;
|
if (result.canceled) return;
|
||||||
selectPgpKeyUi('#pgp-server-name').value = '';
|
selectPgpKeyUi('#pgp-server-name').value = '';
|
||||||
selectPgpKeyUi('#pgp-server-url').value = '';
|
selectPgpKeyUi('#pgp-server-url').value = '';
|
||||||
await renderKeyServers();
|
await renderKeyServers();
|
||||||
status('Custom key server added.');
|
status('Custom key server added.');
|
||||||
} catch (error) { status(error.message || 'Could not add the key server.'); }
|
} catch (error) { status(error.message || 'Could not add the key server.'); }
|
||||||
finally { button.disabled = false; }
|
finally { button.disabled = false; }
|
||||||
};
|
};
|
||||||
window.daybreakMail.pgp.getSettings().then(settings => { selectPgpKeyUi('#pgp-cache-minutes').value = settings.cacheMinutes; }).catch(() => {});
|
window.daybreakMail.pgp.getSettings().then(settings => { selectPgpKeyUi('#pgp-cache-minutes').value = settings.cacheMinutes; }).catch(() => {});
|
||||||
selectPgpKeyUi('#pgp-save-cache').onclick = async () => {
|
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).`); }
|
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.'); }
|
||||||
};
|
};
|
||||||
selectPgpKeyUi('#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 renderKeyServers();
|
||||||
void renderContacts();
|
void renderContacts();
|
||||||
void render();
|
void render();
|
||||||
}
|
}
|
||||||
|
|
||||||
window.epMailFeatures.productivity.wrapOpenPreferences(baseOpenPreferences => function () {
|
window.epMailFeatures.productivity.wrapOpenPreferences(baseOpenPreferences => function () {
|
||||||
baseOpenPreferences();
|
baseOpenPreferences();
|
||||||
const fields = selectPgpKeyUi('#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';
|
||||||
button.className = 'discard';
|
button.className = 'discard';
|
||||||
button.id = 'open-encryption-keys';
|
button.id = 'open-encryption-keys';
|
||||||
button.textContent = 'Encryption keys…';
|
button.textContent = 'Encryption keys…';
|
||||||
button.onclick = openEncryptionKeys;
|
button.onclick = openEncryptionKeys;
|
||||||
fields.append(button);
|
fields.append(button);
|
||||||
});
|
});
|
||||||
})();
|
})();
|
||||||
|
|||||||
@@ -6,50 +6,50 @@ const selectAllProductivityUi = productivityMailUi.selectAll;
|
|||||||
const toastProductivityUi = productivityMailUi.toast;
|
const toastProductivityUi = productivityMailUi.toast;
|
||||||
const escapeProductivityUi = productivityMailUi.escapeHtml;
|
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));
|
||||||
let profileSettings = productRead(productKeys.profile, { name: '' });
|
let profileSettings = productRead(productKeys.profile, { name: '' });
|
||||||
if (/^mira(\s+sol)?$/i.test(profileSettings.name || '')) { profileSettings = { name: '' }; localStorage.removeItem(productKeys.profile); }
|
if (/^mira(\s+sol)?$/i.test(profileSettings.name || '')) { profileSettings = { name: '' }; localStorage.removeItem(productKeys.profile); }
|
||||||
let calendarMonth = new Date(new Date().getFullYear(), new Date().getMonth(), 1);
|
let calendarMonth = new Date(new Date().getFullYear(), new Date().getMonth(), 1);
|
||||||
const generatedContactEmails = new Set(['amelia@northstar.design','jonah@fieldnotes.co','sofia@smallhours.works','mateo@roam.travel','eden@paperandpine.com','noah@common-thread.org','iris@littlefern.press']);
|
const generatedContactEmails = new Set(['amelia@northstar.design','jonah@fieldnotes.co','sofia@smallhours.works','mateo@roam.travel','eden@paperandpine.com','noah@common-thread.org','iris@littlefern.press']);
|
||||||
let savedContacts = productRead(productKeys.contacts, []).filter(contact => !generatedContactEmails.has(String(contact.email||'').toLowerCase()));
|
let savedContacts = productRead(productKeys.contacts, []).filter(contact => !generatedContactEmails.has(String(contact.email||'').toLowerCase()));
|
||||||
productWrite(productKeys.contacts, savedContacts);
|
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=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 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=selectProductivityUi('#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="${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>`;
|
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='';
|
||||||
selectAllProductivityUi('.modal-close').forEach(button=>button.onclick=close);
|
selectAllProductivityUi('.modal-close').forEach(button=>button.onclick=close);
|
||||||
selectProductivityUi('.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()};
|
||||||
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')};
|
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')};
|
||||||
selectProductivityUi('#profile-name').focus();
|
selectProductivityUi('#profile-name').focus();
|
||||||
}
|
}
|
||||||
function openPreferences() {
|
function openPreferences() {
|
||||||
const root=selectProductivityUi('#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='';
|
||||||
selectAllProductivityUi('.modal-close').forEach(button=>button.onclick=close);
|
selectAllProductivityUi('.modal-close').forEach(button=>button.onclick=close);
|
||||||
selectProductivityUi('.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()};
|
||||||
selectProductivityUi('#save-appearance').onclick=()=>{productivityMailUi.applyTheme(selectProductivityUi('#theme-select').value);close();toastProductivityUi('Appearance saved')};
|
selectProductivityUi('#save-appearance').onclick=()=>{productivityMailUi.applyTheme(selectProductivityUi('#theme-select').value);close();toastProductivityUi('Appearance saved')};
|
||||||
selectProductivityUi('#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=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 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}">${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 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=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 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:${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 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((productivityMailUi.connectedAccount?.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=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 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())){toastProductivityUi('That label already exists');return}customLabels.push(clean);productWrite(productKeys.labels,customLabels);renderLabels();toastProductivityUi('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(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()}
|
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=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')}}
|
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();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 ↓';});
|
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);toastProductivityUi(`Labeled ${label}`);productivityMailUi.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()}
|
||||||
productivityMailUi.wrapRenderList(baseMessageRenderer => function () {
|
productivityMailUi.wrapRenderList(baseMessageRenderer => function () {
|
||||||
const state = productivityMailUi.state;
|
const state = productivityMailUi.state;
|
||||||
if (state.activeFolder === 'Drafts') {
|
if (state.activeFolder === 'Drafts') {
|
||||||
@@ -71,7 +71,7 @@ productivityMailUi.wrapRenderList(baseMessageRenderer => function () {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
return baseMessageRenderer();
|
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);
|
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({
|
window.epMailFeatures.productivity = Object.freeze({
|
||||||
|
|||||||
@@ -1,40 +1,40 @@
|
|||||||
import { Capacitor, registerPlugin } from '@capacitor/core';
|
import { Capacitor, registerPlugin } from '@capacitor/core';
|
||||||
|
|
||||||
const EpMail = registerPlugin('EpMail');
|
const EpMail = registerPlugin('EpMail');
|
||||||
|
|
||||||
if (Capacitor.isNativePlatform() && Capacitor.getPlatform() === 'android') {
|
if (Capacitor.isNativePlatform() && Capacitor.getPlatform() === 'android') {
|
||||||
window.daybreakMail = {
|
window.daybreakMail = {
|
||||||
getAppVersion: () => EpMail.getAppVersion().then(result => result.version),
|
getAppVersion: () => EpMail.getAppVersion().then(result => result.version),
|
||||||
getAccount: () => EpMail.getAccount(),
|
getAccount: () => EpMail.getAccount(),
|
||||||
listAccounts: () => EpMail.listAccounts(),
|
listAccounts: () => EpMail.listAccounts(),
|
||||||
selectAccount: id => EpMail.selectAccount({ id }),
|
selectAccount: id => EpMail.selectAccount({ id }),
|
||||||
removeAccount: id => EpMail.removeAccount({ id }),
|
removeAccount: id => EpMail.removeAccount({ id }),
|
||||||
connect: details => EpMail.connect(details),
|
connect: details => EpMail.connect(details),
|
||||||
updateAccount: (id, details) => EpMail.updateAccount({ id, ...details }),
|
updateAccount: (id, details) => EpMail.updateAccount({ id, ...details }),
|
||||||
syncFolder: (folder, offset, filters) => EpMail.syncFolder({ folder, offset, filters }),
|
syncFolder: (folder, offset, filters) => EpMail.syncFolder({ folder, offset, filters }),
|
||||||
listFolders: () => EpMail.listFolders(),
|
listFolders: () => EpMail.listFolders(),
|
||||||
createFolder: name => EpMail.createFolder({ name }),
|
createFolder: name => EpMail.createFolder({ name }),
|
||||||
listDrafts: () => EpMail.listDrafts(),
|
listDrafts: () => EpMail.listDrafts(),
|
||||||
saveDraft: draft => EpMail.saveDraft(draft),
|
saveDraft: draft => EpMail.saveDraft(draft),
|
||||||
deleteDraft: id => EpMail.deleteDraft({ id }),
|
deleteDraft: id => EpMail.deleteDraft({ id }),
|
||||||
syncInbox: () => EpMail.syncFolder({ folder: 'Inbox', offset: 0 }),
|
syncInbox: () => EpMail.syncFolder({ folder: 'Inbox', offset: 0 }),
|
||||||
onSyncUpdate: callback => EpMail.addListener('mailSyncUpdate', callback),
|
onSyncUpdate: callback => EpMail.addListener('mailSyncUpdate', callback),
|
||||||
updateMessage: details => EpMail.updateMessage(details),
|
updateMessage: details => EpMail.updateMessage(details),
|
||||||
setSnooze: details => EpMail.setSnooze(details),
|
setSnooze: details => EpMail.setSnooze(details),
|
||||||
checkSnoozeReminders: () => EpMail.checkSnoozeReminders(),
|
checkSnoozeReminders: () => EpMail.checkSnoozeReminders(),
|
||||||
previewAttachment: details => EpMail.previewAttachment(details),
|
previewAttachment: details => EpMail.previewAttachment(details),
|
||||||
saveAttachment: details => EpMail.saveAttachment(details),
|
saveAttachment: details => EpMail.saveAttachment(details),
|
||||||
openExternal: url => EpMail.openExternal({ url }),
|
openExternal: url => EpMail.openExternal({ url }),
|
||||||
send: message => EpMail.send(message),
|
send: message => EpMail.send(message),
|
||||||
disconnect: id => EpMail.removeAccount({ id }),
|
disconnect: id => EpMail.removeAccount({ id }),
|
||||||
davList: () => EpMail.davList(),
|
davList: () => EpMail.davList(),
|
||||||
davConnect: config => EpMail.davConnect(config),
|
davConnect: config => EpMail.davConnect(config),
|
||||||
davActivate: (type, id) => EpMail.davActivate({ type, id }),
|
davActivate: (type, id) => EpMail.davActivate({ type, id }),
|
||||||
davRemove: (type, id) => EpMail.davRemove({ type, id }),
|
davRemove: (type, id) => EpMail.davRemove({ type, id }),
|
||||||
davSync: type => EpMail.davSync({ type }),
|
davSync: type => EpMail.davSync({ type }),
|
||||||
davSaveEvent: event => EpMail.davSaveEvent(event),
|
davSaveEvent: event => EpMail.davSaveEvent(event),
|
||||||
davDeleteEvent: remote => EpMail.davDeleteEvent(remote),
|
davDeleteEvent: remote => EpMail.davDeleteEvent(remote),
|
||||||
davSaveContact: contact => EpMail.davSaveContact(contact),
|
davSaveContact: contact => EpMail.davSaveContact(contact),
|
||||||
davDeleteContact: remote => EpMail.davDeleteContact(remote)
|
davDeleteContact: remote => EpMail.davDeleteContact(remote)
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,19 +1,19 @@
|
|||||||
# Builds the Android APK and the Windows portable exe into .\release
|
# Builds the Android APK and the Windows portable exe into .\release
|
||||||
$ErrorActionPreference = 'Stop'
|
$ErrorActionPreference = 'Stop'
|
||||||
Set-Location $PSScriptRoot\..
|
Set-Location $PSScriptRoot\..
|
||||||
$version = (Get-Content package.json -Raw | ConvertFrom-Json).version
|
$version = (Get-Content package.json -Raw | ConvertFrom-Json).version
|
||||||
if (-not $env:JAVA_HOME) { $env:JAVA_HOME = 'C:\Program Files\Android\Android Studio\jbr' }
|
if (-not $env:JAVA_HOME) { $env:JAVA_HOME = 'C:\Program Files\Android\Android Studio\jbr' }
|
||||||
if (-not $env:ANDROID_HOME) { $env:ANDROID_HOME = Join-Path $env:LOCALAPPDATA 'Android\Sdk' }
|
if (-not $env:ANDROID_HOME) { $env:ANDROID_HOME = Join-Path $env:LOCALAPPDATA 'Android\Sdk' }
|
||||||
New-Item -ItemType Directory -Force release | Out-Null
|
New-Item -ItemType Directory -Force release | Out-Null
|
||||||
|
|
||||||
Write-Host "== Building APK $version =="
|
Write-Host "== Building APK $version =="
|
||||||
npm run android:apk
|
npm run android:apk
|
||||||
if ($LASTEXITCODE) { throw 'APK build failed' }
|
if ($LASTEXITCODE) { throw 'APK build failed' }
|
||||||
Copy-Item android\app\build\outputs\apk\debug\app-debug.apk "release\ep-mail $version.apk" -Force
|
Copy-Item android\app\build\outputs\apk\debug\app-debug.apk "release\ep-mail $version.apk" -Force
|
||||||
|
|
||||||
Write-Host "== Building portable exe $version =="
|
Write-Host "== Building portable exe $version =="
|
||||||
npm run dist:win:portable
|
npm run dist:win:portable
|
||||||
if ($LASTEXITCODE) { throw 'Portable build failed' }
|
if ($LASTEXITCODE) { throw 'Portable build failed' }
|
||||||
|
|
||||||
Write-Host "`nDone:"
|
Write-Host "`nDone:"
|
||||||
Get-ChildItem release | Where-Object { $_.Name -like "ep-mail $version.*" } | ForEach-Object { " $($_.FullName)" }
|
Get-ChildItem release | Where-Object { $_.Name -like "ep-mail $version.*" } | ForEach-Object { " $($_.FullName)" }
|
||||||
@@ -1,27 +1,27 @@
|
|||||||
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 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';
|
||||||
const result = spawnSync(gradleWrapper, ['assembleDebug'], {
|
const result = spawnSync(gradleWrapper, ['assembleDebug'], {
|
||||||
cwd: androidDir,
|
cwd: androidDir,
|
||||||
stdio: 'inherit',
|
stdio: 'inherit',
|
||||||
shell: process.platform === 'win32'
|
shell: process.platform === 'win32'
|
||||||
});
|
});
|
||||||
|
|
||||||
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) {
|
} else if (result.status !== 0) {
|
||||||
process.exitCode = result.status;
|
process.exitCode = result.status || 1;
|
||||||
} else {
|
} else {
|
||||||
const root = path.resolve(__dirname, '..');
|
const root = path.resolve(__dirname, '..');
|
||||||
const { version } = require(path.join(root, 'package.json'));
|
const { version } = require(path.join(root, 'package.json'));
|
||||||
const apk = path.join(androidDir, 'app', 'build', 'outputs', 'apk', 'debug', 'app-debug.apk');
|
const apk = path.join(androidDir, 'app', 'build', 'outputs', 'apk', 'debug', 'app-debug.apk');
|
||||||
const releaseDir = path.join(root, 'release');
|
const releaseDir = path.join(root, 'release');
|
||||||
const target = path.join(releaseDir, `ep-mail ${version}.apk`);
|
const target = path.join(releaseDir, `ep-mail ${version}-debug.apk`);
|
||||||
fs.mkdirSync(releaseDir, { recursive: true });
|
fs.mkdirSync(releaseDir, { recursive: true });
|
||||||
fs.copyFileSync(apk, target);
|
fs.copyFileSync(apk, target);
|
||||||
console.log(`APK copied to ${target}`);
|
console.log(`Debug APK copied to ${target}`);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
const { spawnSync } = require('node:child_process');
|
||||||
|
const path = require('node:path');
|
||||||
|
const fs = require('node:fs');
|
||||||
|
|
||||||
|
const requiredSigningVariables = [
|
||||||
|
'EP_MAIL_ANDROID_STORE_FILE',
|
||||||
|
'EP_MAIL_ANDROID_STORE_PASSWORD',
|
||||||
|
'EP_MAIL_ANDROID_KEY_ALIAS',
|
||||||
|
'EP_MAIL_ANDROID_KEY_PASSWORD'
|
||||||
|
];
|
||||||
|
const missing = requiredSigningVariables.filter(name => !process.env[name]);
|
||||||
|
if (missing.length) {
|
||||||
|
console.error(`Signed Android release requires these environment variables: ${missing.join(', ')}`);
|
||||||
|
process.exitCode = 1;
|
||||||
|
} else if (!path.isAbsolute(process.env.EP_MAIL_ANDROID_STORE_FILE)) {
|
||||||
|
console.error('EP_MAIL_ANDROID_STORE_FILE must be an absolute path.');
|
||||||
|
process.exitCode = 1;
|
||||||
|
} else {
|
||||||
|
const androidDir = path.resolve(__dirname, '..', 'android');
|
||||||
|
const gradleWrapper = process.platform === 'win32' ? 'gradlew.bat' : './gradlew';
|
||||||
|
const result = spawnSync(gradleWrapper, ['assembleRelease'], {
|
||||||
|
cwd: androidDir,
|
||||||
|
stdio: 'inherit',
|
||||||
|
shell: process.platform === 'win32'
|
||||||
|
});
|
||||||
|
|
||||||
|
if (result.error) {
|
||||||
|
console.error(`Could not start the Android Gradle wrapper: ${result.error.message}`);
|
||||||
|
process.exitCode = 1;
|
||||||
|
} else if (result.status !== 0) {
|
||||||
|
process.exitCode = result.status || 1;
|
||||||
|
} else {
|
||||||
|
const root = path.resolve(__dirname, '..');
|
||||||
|
const { version } = require(path.join(root, 'package.json'));
|
||||||
|
const apk = path.join(androidDir, 'app', 'build', 'outputs', 'apk', 'release', 'app-release.apk');
|
||||||
|
const releaseDir = path.join(root, 'release');
|
||||||
|
const target = path.join(releaseDir, `ep-mail ${version}.apk`);
|
||||||
|
if (!fs.existsSync(apk)) {
|
||||||
|
console.error(`Gradle did not produce the expected release APK: ${apk}`);
|
||||||
|
process.exitCode = 1;
|
||||||
|
} else {
|
||||||
|
fs.mkdirSync(releaseDir, { recursive: true });
|
||||||
|
fs.copyFileSync(apk, target);
|
||||||
|
console.log(`Signed release APK copied to ${target}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,52 +1,52 @@
|
|||||||
const fs = require('node:fs/promises');
|
const fs = require('node:fs/promises');
|
||||||
const path = require('node:path');
|
const path = require('node:path');
|
||||||
const esbuild = require('esbuild');
|
const esbuild = require('esbuild');
|
||||||
|
|
||||||
const root = path.resolve(__dirname, '..');
|
const root = path.resolve(__dirname, '..');
|
||||||
const output = path.join(root, 'www');
|
const output = path.join(root, 'www');
|
||||||
const assets = [
|
const assets = [
|
||||||
'index.html',
|
'index.html',
|
||||||
'styles.css',
|
'styles.css',
|
||||||
'branding.css',
|
'branding.css',
|
||||||
'platform-bridge-loader.js',
|
'platform-bridge-loader.js',
|
||||||
'renderer-state.js',
|
'renderer-state.js',
|
||||||
'mail-content-security.js',
|
'mail-content-security.js',
|
||||||
'renderer-mail-api.js',
|
'renderer-mail-api.js',
|
||||||
'app.js',
|
'app.js',
|
||||||
'mail-ui.js',
|
'mail-ui.js',
|
||||||
'productivity.js',
|
'productivity.js',
|
||||||
'account-ui.js',
|
'account-ui.js',
|
||||||
'dav-ui.js',
|
'dav-ui.js',
|
||||||
'shortcuts.js',
|
'shortcuts.js',
|
||||||
'attachments.js',
|
'attachments.js',
|
||||||
'pgp-ui.js',
|
'pgp-ui.js',
|
||||||
'pgp-mail-ui.js',
|
'pgp-mail-ui.js',
|
||||||
'icon.svg',
|
'icon.svg',
|
||||||
'logo-ep-daylight.svg',
|
'logo-ep-daylight.svg',
|
||||||
'logo-ep-wasteland.svg',
|
'logo-ep-wasteland.svg',
|
||||||
'manifest.webmanifest',
|
'manifest.webmanifest',
|
||||||
'service-worker.js',
|
'service-worker.js',
|
||||||
'snooze-ui.js'
|
'snooze-ui.js'
|
||||||
];
|
];
|
||||||
|
|
||||||
async function prepare() {
|
async function prepare() {
|
||||||
await fs.rm(output, { recursive: true, force: true });
|
await fs.rm(output, { recursive: true, force: true });
|
||||||
await fs.mkdir(output, { recursive: true });
|
await fs.mkdir(output, { recursive: true });
|
||||||
for (const asset of assets) {
|
for (const asset of assets) {
|
||||||
await fs.copyFile(path.join(root, asset), path.join(output, asset));
|
await fs.copyFile(path.join(root, asset), path.join(output, asset));
|
||||||
}
|
}
|
||||||
const bridgePath = path.join(root, 'platform-bridge.js');
|
const bridgePath = path.join(root, 'platform-bridge.js');
|
||||||
await esbuild.build({
|
await esbuild.build({
|
||||||
entryPoints: [path.join(root, 'scripts', 'android-bridge.js')],
|
entryPoints: [path.join(root, 'scripts', 'android-bridge.js')],
|
||||||
outfile: bridgePath,
|
outfile: bridgePath,
|
||||||
bundle: true,
|
bundle: true,
|
||||||
platform: 'browser',
|
platform: 'browser',
|
||||||
format: 'iife'
|
format: 'iife'
|
||||||
});
|
});
|
||||||
await fs.copyFile(bridgePath, path.join(output, 'platform-bridge.js'));
|
await fs.copyFile(bridgePath, path.join(output, 'platform-bridge.js'));
|
||||||
}
|
}
|
||||||
|
|
||||||
prepare().catch(error => {
|
prepare().catch(error => {
|
||||||
console.error('Could not prepare Android web assets:', error);
|
console.error('Could not prepare Android web assets:', error);
|
||||||
process.exitCode = 1;
|
process.exitCode = 1;
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
const CACHE='ep-mail-v12';
|
const CACHE='ep-mail-v12';
|
||||||
const FILES=['./','./index.html','./styles.css','./branding.css','./renderer-state.js','./mail-content-security.js','./renderer-mail-api.js','./app.js','./platform-bridge-loader.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-loader.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'))))});
|
||||||
|
|||||||
@@ -6,102 +6,102 @@ const selectShortcutUi = shortcutMailUi.select;
|
|||||||
const toastShortcutUi = shortcutMailUi.toast;
|
const toastShortcutUi = shortcutMailUi.toast;
|
||||||
const escapeShortcutUi = shortcutMailUi.escapeHtml;
|
const escapeShortcutUi = shortcutMailUi.escapeHtml;
|
||||||
const shortcutStorageKey = 'daybreak-shortcuts';
|
const shortcutStorageKey = 'daybreak-shortcuts';
|
||||||
const shortcutActions = [
|
const shortcutActions = [
|
||||||
{ id: 'compose', label: 'Compose', fallback: 'c', run: () => selectShortcutUi('#compose')?.click() },
|
{ id: 'compose', label: 'Compose', fallback: 'c', run: () => selectShortcutUi('#compose')?.click() },
|
||||||
{ id: 'search', label: 'Search', fallback: '/', run: () => selectShortcutUi('#search')?.focus() },
|
{ id: 'search', label: 'Search', fallback: '/', run: () => selectShortcutUi('#search')?.focus() },
|
||||||
{ id: 'refresh', label: 'Refresh', fallback: 'r', run: () => selectShortcutUi('#refresh')?.click() },
|
{ id: 'refresh', label: 'Refresh', fallback: 'r', run: () => selectShortcutUi('#refresh')?.click() },
|
||||||
{ id: 'archive', label: 'Archive message', fallback: 'e', run: () => selectShortcutUi('#reader-archive')?.click() },
|
{ id: 'archive', label: 'Archive message', fallback: 'e', run: () => selectShortcutUi('#reader-archive')?.click() },
|
||||||
{ id: 'delete', label: 'Delete message', fallback: '#', run: () => selectShortcutUi('#reader-delete')?.click() },
|
{ id: 'delete', label: 'Delete message', fallback: '#', run: () => selectShortcutUi('#reader-delete')?.click() },
|
||||||
{ id: 'star', label: 'Star message', fallback: 's', run: () => selectShortcutUi('#reader-star')?.click() },
|
{ id: 'star', label: 'Star message', fallback: 's', run: () => selectShortcutUi('#reader-star')?.click() },
|
||||||
{ id: 'reply', label: 'Reply', fallback: 'a', run: () => selectShortcutUi('#reply')?.click() },
|
{ id: 'reply', label: 'Reply', fallback: 'a', run: () => selectShortcutUi('#reply')?.click() },
|
||||||
{ id: 'forward', label: 'Forward', fallback: 'f', run: () => selectShortcutUi('#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) }
|
||||||
];
|
];
|
||||||
|
|
||||||
function normalizeShortcut(value) {
|
function normalizeShortcut(value) {
|
||||||
const text = String(value || '').trim();
|
const text = String(value || '').trim();
|
||||||
if (!text) return '';
|
if (!text) return '';
|
||||||
const parts = text.split('+').map(part => part.trim()).filter(Boolean);
|
const parts = text.split('+').map(part => part.trim()).filter(Boolean);
|
||||||
const key = parts.pop() || '+';
|
const key = parts.pop() || '+';
|
||||||
const mods = ['Ctrl', 'Alt', 'Shift'].filter(mod => parts.some(part => part.toLowerCase() === mod.toLowerCase()));
|
const mods = ['Ctrl', 'Alt', 'Shift'].filter(mod => parts.some(part => part.toLowerCase() === mod.toLowerCase()));
|
||||||
return [...mods, key.length === 1 ? key.toLowerCase() : key].join('+');
|
return [...mods, key.length === 1 ? key.toLowerCase() : key].join('+');
|
||||||
}
|
}
|
||||||
|
|
||||||
function loadShortcuts() {
|
function loadShortcuts() {
|
||||||
let saved = {};
|
let saved = {};
|
||||||
try { saved = JSON.parse(localStorage.getItem(shortcutStorageKey)) || {}; } catch {}
|
try { saved = JSON.parse(localStorage.getItem(shortcutStorageKey)) || {}; } catch {}
|
||||||
return Object.fromEntries(shortcutActions.map(action => [
|
return Object.fromEntries(shortcutActions.map(action => [
|
||||||
action.id, typeof saved[action.id] === 'string' ? normalizeShortcut(saved[action.id]) : action.fallback
|
action.id, typeof saved[action.id] === 'string' ? normalizeShortcut(saved[action.id]) : action.fallback
|
||||||
]));
|
]));
|
||||||
}
|
}
|
||||||
|
|
||||||
function eventShortcut(event) {
|
function eventShortcut(event) {
|
||||||
if (['Control', 'Alt', 'Shift', 'Meta'].includes(event.key)) return '';
|
if (['Control', 'Alt', 'Shift', 'Meta'].includes(event.key)) return '';
|
||||||
const mods = [event.ctrlKey || event.metaKey ? 'Ctrl' : '', event.altKey ? 'Alt' : ''];
|
const mods = [event.ctrlKey || event.metaKey ? 'Ctrl' : '', event.altKey ? 'Alt' : ''];
|
||||||
const printable = event.key.length === 1;
|
const printable = event.key.length === 1;
|
||||||
if (event.shiftKey && !printable) mods.push('Shift');
|
if (event.shiftKey && !printable) mods.push('Shift');
|
||||||
return normalizeShortcut([...mods.filter(Boolean), event.key === ' ' ? 'Space' : event.key].join('+'));
|
return normalizeShortcut([...mods.filter(Boolean), event.key === ' ' ? 'Space' : event.key].join('+'));
|
||||||
}
|
}
|
||||||
|
|
||||||
function moveMessageSelection(step) {
|
function moveMessageSelection(step) {
|
||||||
const messages = shortcutMailUi.state.messages;
|
const messages = shortcutMailUi.state.messages;
|
||||||
if (!messages.length) return;
|
if (!messages.length) return;
|
||||||
const index = messages.findIndex(message => message.id === shortcutMailUi.state.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) { shortcutMailUi.openMessage(next.id); selectShortcutUi(`.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"]') || selectShortcutUi('#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();
|
||||||
const action = shortcutActions.find(item => shortcuts[item.id] && shortcuts[item.id] === pressed);
|
const action = shortcutActions.find(item => shortcuts[item.id] && shortcuts[item.id] === pressed);
|
||||||
if (!action) return;
|
if (!action) return;
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
action.run();
|
action.run();
|
||||||
});
|
});
|
||||||
|
|
||||||
shortcutProductivityUi.wrapOpenPreferences(baseOpenPreferences => function () {
|
shortcutProductivityUi.wrapOpenPreferences(baseOpenPreferences => function () {
|
||||||
baseOpenPreferences();
|
baseOpenPreferences();
|
||||||
const fields = selectShortcutUi('#modal-root .compose-fields');
|
const fields = selectShortcutUi('#modal-root .compose-fields');
|
||||||
const save = selectShortcutUi('#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="${escapeShortcutUi(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');
|
||||||
if (!input || ['Tab', 'Escape'].includes(event.key)) return;
|
if (!input || ['Tab', 'Escape'].includes(event.key)) return;
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
if (['Backspace', 'Delete'].includes(event.key)) { input.value = ''; return; }
|
if (['Backspace', 'Delete'].includes(event.key)) { input.value = ''; return; }
|
||||||
const combo = eventShortcut(event);
|
const combo = eventShortcut(event);
|
||||||
if (combo) input.value = combo;
|
if (combo) input.value = combo;
|
||||||
});
|
});
|
||||||
selectShortcutUi('#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;
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
const baseSave = save.onclick;
|
const baseSave = save.onclick;
|
||||||
save.onclick = event => {
|
save.onclick = event => {
|
||||||
const values = {};
|
const values = {};
|
||||||
const used = new Map();
|
const used = new Map();
|
||||||
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)) { toastShortcutUi(`“${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);
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
})();
|
})();
|
||||||
|
|||||||
@@ -3,91 +3,91 @@ const snoozeMailUi = window.epMailFeatures.mail;
|
|||||||
const snoozeProductivityUi = window.epMailFeatures.productivity;
|
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);
|
||||||
}
|
}
|
||||||
|
|
||||||
function nextMorning(daysAhead) {
|
function nextMorning(daysAhead) {
|
||||||
const date = new Date();
|
const date = new Date();
|
||||||
date.setDate(date.getDate() + daysAhead);
|
date.setDate(date.getDate() + daysAhead);
|
||||||
date.setHours(9, 0, 0, 0);
|
date.setHours(9, 0, 0, 0);
|
||||||
if (date <= new Date()) date.setDate(date.getDate() + 1);
|
if (date <= new Date()) date.setDate(date.getDate() + 1);
|
||||||
return date;
|
return date;
|
||||||
}
|
}
|
||||||
|
|
||||||
function openSnoozeDialog(items) {
|
function openSnoozeDialog(items) {
|
||||||
const eligible = items.filter(message => message?.uid && snoozeMailUi.connectedAccount);
|
const eligible = items.filter(message => message?.uid && snoozeMailUi.connectedAccount);
|
||||||
if (!eligible.length) {
|
if (!eligible.length) {
|
||||||
snoozeMailUi.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 = snoozeMailUi.select('#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>`;
|
||||||
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 => {
|
root.querySelector('.modal-overlay').onclick = event => {
|
||||||
if (event.target.classList.contains('modal-overlay')) close();
|
if (event.target.classList.contains('modal-overlay')) close();
|
||||||
};
|
};
|
||||||
|
|
||||||
const schedule = async dueAt => {
|
const schedule = async dueAt => {
|
||||||
if (!Number.isFinite(dueAt) || dueAt <= Date.now()) {
|
if (!Number.isFinite(dueAt) || dueAt <= Date.now()) {
|
||||||
snoozeMailUi.select('#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')];
|
||||||
buttons.forEach(button => { button.disabled = true; });
|
buttons.forEach(button => { button.disabled = true; });
|
||||||
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(snoozeMailUi.state.activeFolder) ? snoozeMailUi.state.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,
|
||||||
sourceFolder,
|
sourceFolder,
|
||||||
dueAt,
|
dueAt,
|
||||||
subject: message.subject
|
subject: message.subject
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
close();
|
close();
|
||||||
snoozeMailUi.toast(eligible.length === 1 ? 'Message snoozed' : `${eligible.length} messages snoozed`);
|
snoozeMailUi.toast(eligible.length === 1 ? 'Message snoozed' : `${eligible.length} messages snoozed`);
|
||||||
snoozeMailUi.state.selectedIds.clear();
|
snoozeMailUi.state.selectedIds.clear();
|
||||||
await snoozeMailUi.syncMailbox(false, { offset: 0 });
|
await snoozeMailUi.syncMailbox(false, { offset: 0 });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
snoozeMailUi.select('#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; });
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
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));
|
||||||
});
|
});
|
||||||
snoozeMailUi.select('#snooze-custom').onclick = () => schedule(new Date(snoozeMailUi.select('#snooze-custom-time').value).getTime());
|
snoozeMailUi.select('#snooze-custom').onclick = () => schedule(new Date(snoozeMailUi.select('#snooze-custom-time').value).getTime());
|
||||||
snoozeMailUi.select('#snooze-custom-time').focus();
|
snoozeMailUi.select('#snooze-custom-time').focus();
|
||||||
}
|
}
|
||||||
|
|
||||||
function unsnoozeMessage(message) {
|
function unsnoozeMessage(message) {
|
||||||
const sourceFolder = message.sourceFolder || 'Inbox';
|
const sourceFolder = message.sourceFolder || 'Inbox';
|
||||||
window.daybreakMail.setSnooze({
|
window.daybreakMail.setSnooze({
|
||||||
uid: message.uid,
|
uid: message.uid,
|
||||||
sourceFolder,
|
sourceFolder,
|
||||||
dueAt: null
|
dueAt: null
|
||||||
}).then(async () => {
|
}).then(async () => {
|
||||||
snoozeMailUi.toast('Message returned to its mailbox');
|
snoozeMailUi.toast('Message returned to its mailbox');
|
||||||
await snoozeMailUi.syncMailbox(false, { offset: 0 });
|
await snoozeMailUi.syncMailbox(false, { offset: 0 });
|
||||||
}).catch(error => snoozeMailUi.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 = snoozeMailUi.select('#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 => {
|
||||||
if (event.target.classList.contains('modal-overlay')) root.innerHTML = '';
|
if (event.target.classList.contains('modal-overlay')) root.innerHTML = '';
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
snoozeMailUi.wrapRenderList(renderListBeforeSnooze => function () {
|
snoozeMailUi.wrapRenderList(renderListBeforeSnooze => function () {
|
||||||
if (snoozeMailUi.state.activeFolder === 'Snoozed') {
|
if (snoozeMailUi.state.activeFolder === 'Snoozed') {
|
||||||
const originalMessages = snoozeMailUi.state.messages.slice();
|
const originalMessages = snoozeMailUi.state.messages.slice();
|
||||||
@@ -99,21 +99,21 @@ snoozeMailUi.wrapRenderList(renderListBeforeSnooze => function () {
|
|||||||
snoozeMailUi.state.activeFolder = 'Inbox';
|
snoozeMailUi.state.activeFolder = 'Inbox';
|
||||||
snoozeMailUi.baseRenderList();
|
snoozeMailUi.baseRenderList();
|
||||||
snoozeMailUi.state.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;
|
||||||
});
|
});
|
||||||
snoozeMailUi.state.messages.splice(0, snoozeMailUi.state.messages.length, ...originalMessages);
|
snoozeMailUi.state.messages.splice(0, snoozeMailUi.state.messages.length, ...originalMessages);
|
||||||
for (const row of snoozeMailUi.selectAll('.message')) {
|
for (const row of snoozeMailUi.selectAll('.message')) {
|
||||||
const message = snoozeMailUi.state.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()}`;
|
||||||
const snippet = row.querySelector('.snippet');
|
const snippet = row.querySelector('.snippet');
|
||||||
if (snippet) snippet.textContent = `Reminder · ${due.toLocaleString()} · ${message.snippet}`;
|
if (snippet) snippet.textContent = `Reminder · ${due.toLocaleString()} · ${message.snippet}`;
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
return renderListBeforeSnooze();
|
return renderListBeforeSnooze();
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -121,61 +121,61 @@ snoozeMailUi.wrapOpenMessage(openMessageBeforeSnooze => function (id) {
|
|||||||
openMessageBeforeSnooze(id);
|
openMessageBeforeSnooze(id);
|
||||||
const message = snoozeMailUi.state.messages.find(item => item.id === id);
|
const message = snoozeMailUi.state.messages.find(item => item.id === id);
|
||||||
const tools = snoozeMailUi.select('.reader-tools');
|
const tools = snoozeMailUi.select('.reader-tools');
|
||||||
if (!message || !tools) return;
|
if (!message || !tools) return;
|
||||||
const snoozed = snoozeMailUi.state.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', () => {
|
||||||
snoozeMailUi.select('#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));
|
||||||
void checkReminders();
|
void checkReminders();
|
||||||
setInterval(checkReminders, 60 * 1000);
|
setInterval(checkReminders, 60 * 1000);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
document.addEventListener('click', event => {
|
document.addEventListener('click', event => {
|
||||||
const action = event.target.closest('[data-message-action]');
|
const action = event.target.closest('[data-message-action]');
|
||||||
const more = event.target.closest('.reader-tools button[title="More"]');
|
const more = event.target.closest('.reader-tools button[title="More"]');
|
||||||
const snooze = event.target.closest('#reader-snooze, #snooze-selected');
|
const snooze = event.target.closest('#reader-snooze, #snooze-selected');
|
||||||
const unsnooze = event.target.closest('#reader-unsnooze');
|
const unsnooze = event.target.closest('#reader-unsnooze');
|
||||||
if (!more && !snooze && !unsnooze && !action) return;
|
if (!more && !snooze && !unsnooze && !action) return;
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
event.stopImmediatePropagation();
|
event.stopImmediatePropagation();
|
||||||
if (action) {
|
if (action) {
|
||||||
const message = snoozeMailUi.state.messages.find(item => item.id === snoozeMailUi.state.activeMessage);
|
const message = snoozeMailUi.state.messages.find(item => item.id === snoozeMailUi.state.activeMessage);
|
||||||
snoozeMailUi.select('#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') snoozeProductivityUi.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;
|
||||||
snoozeMailUi.renderList();
|
snoozeMailUi.renderList();
|
||||||
snoozeMailUi.toast(type === 'unread' ? 'Marked unread' : 'Moved to Inbox');
|
snoozeMailUi.toast(type === 'unread' ? 'Marked unread' : 'Moved to Inbox');
|
||||||
}).catch(error => snoozeMailUi.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 = snoozeMailUi.state.messages.find(item => item.id === snoozeMailUi.state.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(snoozeMailUi.state.messages.filter(message => snoozeMailUi.state.selectedIds.has(message.id)));
|
openSnoozeDialog(snoozeMailUi.state.messages.filter(message => snoozeMailUi.state.selectedIds.has(message.id)));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (more) {
|
if (more) {
|
||||||
const message = snoozeMailUi.state.messages.find(item => item.id === snoozeMailUi.state.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 = snoozeMailUi.state.messages.find(item => item.id === snoozeMailUi.state.activeMessage);
|
const message = snoozeMailUi.state.messages.find(item => item.id === snoozeMailUi.state.activeMessage);
|
||||||
if (message) openSnoozeDialog([message]);
|
if (message) openSnoozeDialog([message]);
|
||||||
}, true);
|
}, true);
|
||||||
})();
|
})();
|
||||||
|
|||||||
@@ -8,6 +8,8 @@ const packageJson = JSON.parse(fs.readFileSync(path.join(root, 'package.json'),
|
|||||||
const packageLock = JSON.parse(fs.readFileSync(path.join(root, 'package-lock.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 androidBuild = fs.readFileSync(path.join(root, 'android', 'app', 'build.gradle'), 'utf8');
|
||||||
const buildAll = fs.readFileSync(path.join(root, 'scripts', 'build-all.ps1'), 'utf8');
|
const buildAll = fs.readFileSync(path.join(root, 'scripts', 'build-all.ps1'), 'utf8');
|
||||||
|
const androidDebugScript = fs.readFileSync(path.join(root, 'scripts', 'build-android-apk.cjs'), 'utf8');
|
||||||
|
const androidReleaseScript = fs.readFileSync(path.join(root, 'scripts', 'build-android-release-apk.cjs'), 'utf8');
|
||||||
const desktopWorkflow = fs.readFileSync(path.join(root, '.github', 'workflows', 'desktop-build.yml'), 'utf8');
|
const desktopWorkflow = fs.readFileSync(path.join(root, '.github', 'workflows', 'desktop-build.yml'), 'utf8');
|
||||||
|
|
||||||
test('package metadata and lockfile share one release version', () => {
|
test('package metadata and lockfile share one release version', () => {
|
||||||
@@ -32,3 +34,14 @@ test('release scripts and desktop artifact labels use package.json version', ()
|
|||||||
assert.match(desktopWorkflow, /require\('\.\/package\.json'\)\.version/);
|
assert.match(desktopWorkflow, /require\('\.\/package\.json'\)\.version/);
|
||||||
assert.match(desktopWorkflow, /-v\$\{\{ steps\.app-version\.outputs\.version \}\}/);
|
assert.match(desktopWorkflow, /-v\$\{\{ steps\.app-version\.outputs\.version \}\}/);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('Android debug APK is labeled as debug and release APK requires signing credentials', () => {
|
||||||
|
assert.match(androidDebugScript, /assembleDebug/);
|
||||||
|
assert.match(androidDebugScript, /ep-mail \$\{version\}-debug\.apk/);
|
||||||
|
assert.match(androidReleaseScript, /assembleRelease/);
|
||||||
|
assert.match(androidReleaseScript, /EP_MAIL_ANDROID_STORE_FILE/);
|
||||||
|
assert.match(androidReleaseScript, /EP_MAIL_ANDROID_STORE_PASSWORD/);
|
||||||
|
assert.match(androidReleaseScript, /EP_MAIL_ANDROID_KEY_ALIAS/);
|
||||||
|
assert.match(androidReleaseScript, /EP_MAIL_ANDROID_KEY_PASSWORD/);
|
||||||
|
assert.match(androidReleaseScript, /ep-mail \$\{version\}\.apk/);
|
||||||
|
});
|
||||||
|
|||||||
@@ -1,38 +1,38 @@
|
|||||||
const test = require('node:test');
|
const test = require('node:test');
|
||||||
const assert = require('node:assert/strict');
|
const assert = require('node:assert/strict');
|
||||||
const { normalizeOutgoingAttachments, serializeOutgoingAttachments } = require('../desktop/mail-attachments.cjs');
|
const { normalizeOutgoingAttachments, serializeOutgoingAttachments } = require('../desktop/mail-attachments.cjs');
|
||||||
|
|
||||||
test('normalizes attachment metadata and round-trips bytes through serialized drafts and sends', () => {
|
test('normalizes attachment metadata and round-trips bytes through serialized drafts and sends', () => {
|
||||||
const bytes = Buffer.from([0, 1, 2, 127, 128, 255]);
|
const bytes = Buffer.from([0, 1, 2, 127, 128, 255]);
|
||||||
const [file] = normalizeOutgoingAttachments([{
|
const [file] = normalizeOutgoingAttachments([{
|
||||||
filename: 'folder\\report.bin',
|
filename: 'folder\\report.bin',
|
||||||
contentType: 'APPLICATION/OCTET-STREAM',
|
contentType: 'APPLICATION/OCTET-STREAM',
|
||||||
size: 999,
|
size: 999,
|
||||||
contentBase64: bytes.toString('base64')
|
contentBase64: bytes.toString('base64')
|
||||||
}]);
|
}]);
|
||||||
|
|
||||||
assert.equal(file.filename, 'report.bin');
|
assert.equal(file.filename, 'report.bin');
|
||||||
assert.equal(file.contentType, 'application/octet-stream');
|
assert.equal(file.contentType, 'application/octet-stream');
|
||||||
assert.equal(file.size, bytes.length);
|
assert.equal(file.size, bytes.length);
|
||||||
assert.deepEqual(file.content, bytes);
|
assert.deepEqual(file.content, bytes);
|
||||||
const [serialized] = serializeOutgoingAttachments([file]);
|
const [serialized] = serializeOutgoingAttachments([file]);
|
||||||
assert.equal(serialized.contentBase64, bytes.toString('base64'));
|
assert.equal(serialized.contentBase64, bytes.toString('base64'));
|
||||||
assert.equal('content' in serialized, false);
|
assert.equal('content' in serialized, false);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('rejects malformed attachment data and unsafe content types', () => {
|
test('rejects malformed attachment data and unsafe content types', () => {
|
||||||
assert.throws(() => normalizeOutgoingAttachments({}), /attachment list is invalid/);
|
assert.throws(() => normalizeOutgoingAttachments({}), /attachment list is invalid/);
|
||||||
assert.throws(() => normalizeOutgoingAttachments([{ filename: 'x', contentBase64: '***=' }]), /contents.*invalid/);
|
assert.throws(() => normalizeOutgoingAttachments([{ filename: 'x', contentBase64: '***=' }]), /contents.*invalid/);
|
||||||
assert.throws(() => normalizeOutgoingAttachments([{
|
assert.throws(() => normalizeOutgoingAttachments([{
|
||||||
filename: 'x',
|
filename: 'x',
|
||||||
contentType: 'text/plain\r\nBcc: bad@example.com',
|
contentType: 'text/plain\r\nBcc: bad@example.com',
|
||||||
contentBase64: ''
|
contentBase64: ''
|
||||||
}]), /content type.*invalid/);
|
}]), /content type.*invalid/);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('uses fallback names and MIME types for empty metadata', () => {
|
test('uses fallback names and MIME types for empty metadata', () => {
|
||||||
const [file] = normalizeOutgoingAttachments([{ contentBase64: '' }]);
|
const [file] = normalizeOutgoingAttachments([{ contentBase64: '' }]);
|
||||||
assert.equal(file.filename, 'attachment');
|
assert.equal(file.filename, 'attachment');
|
||||||
assert.equal(file.contentType, 'application/octet-stream');
|
assert.equal(file.contentType, 'application/octet-stream');
|
||||||
assert.equal(file.size, 0);
|
assert.equal(file.size, 0);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,104 +1,104 @@
|
|||||||
const test = require('node:test');
|
const test = require('node:test');
|
||||||
const assert = require('node:assert/strict');
|
const assert = require('node:assert/strict');
|
||||||
const { spawnSync } = require('node:child_process');
|
const { spawnSync } = require('node:child_process');
|
||||||
const fs = require('node:fs');
|
const fs = require('node:fs');
|
||||||
const os = require('node:os');
|
const os = require('node:os');
|
||||||
const path = require('node:path');
|
const path = require('node:path');
|
||||||
const { simpleParser } = require('mailparser');
|
const { simpleParser } = require('mailparser');
|
||||||
const { createKeyStore } = require('../desktop/pgp-keystore.cjs');
|
const { createKeyStore } = require('../desktop/pgp-keystore.cjs');
|
||||||
const { createPgpMail, createPassphraseCache } = require('../desktop/pgp-mail.cjs');
|
const { createPgpMail, createPassphraseCache } = require('../desktop/pgp-mail.cjs');
|
||||||
|
|
||||||
const gpgPath = [process.env.GPG_PATH, 'gpg', 'C:\\Program Files\\GnuPG\\bin\\gpg.exe', 'C:\\Program Files (x86)\\GnuPG\\bin\\gpg.exe']
|
const gpgPath = [process.env.GPG_PATH, 'gpg', 'C:\\Program Files\\GnuPG\\bin\\gpg.exe', 'C:\\Program Files (x86)\\GnuPG\\bin\\gpg.exe']
|
||||||
.filter(Boolean).find(candidate => spawnSync(candidate, ['--version']).status === 0);
|
.filter(Boolean).find(candidate => spawnSync(candidate, ['--version']).status === 0);
|
||||||
const skip = gpgPath ? false : 'GnuPG is not installed';
|
const skip = gpgPath ? false : 'GnuPG is not installed';
|
||||||
const PASS = 'interop passphrase';
|
const PASS = 'interop passphrase';
|
||||||
|
|
||||||
function gpgIn(home) {
|
function gpgIn(home) {
|
||||||
return (args, input) => {
|
return (args, input) => {
|
||||||
const result = spawnSync(gpgPath, ['--homedir', home, '--batch', '--yes', '--pinentry-mode', 'loopback', '--passphrase', PASS, '--trust-model', 'always', ...args], { input });
|
const result = spawnSync(gpgPath, ['--homedir', home, '--batch', '--yes', '--pinentry-mode', 'loopback', '--passphrase', PASS, '--trust-model', 'always', ...args], { input });
|
||||||
if (result.status !== 0) throw new Error(`gpg ${args.join(' ')} failed: ${result.stderr}`);
|
if (result.status !== 0) throw new Error(`gpg ${args.join(' ')} failed: ${result.stderr}`);
|
||||||
return { out: result.stdout, err: result.stderr.toString() };
|
return { out: result.stdout, err: result.stderr.toString() };
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async function setup() {
|
async function setup() {
|
||||||
const home = fs.mkdtempSync(path.join(os.tmpdir(), 'ep-gnupg-'));
|
const home = fs.mkdtempSync(path.join(os.tmpdir(), 'ep-gnupg-'));
|
||||||
const gpg = gpgIn(home);
|
const gpg = gpgIn(home);
|
||||||
gpg(['--quick-generate-key', 'Gina Gnu <gina@example.com>', 'ed25519', 'cert', 'never']);
|
gpg(['--quick-generate-key', 'Gina Gnu <gina@example.com>', 'ed25519', 'cert', 'never']);
|
||||||
const fingerprint = /^fpr:::::::::([0-9A-F]+):/m.exec(gpg(['--list-keys', '--with-colons', 'gina@example.com']).out.toString())[1];
|
const fingerprint = /^fpr:::::::::([0-9A-F]+):/m.exec(gpg(['--list-keys', '--with-colons', 'gina@example.com']).out.toString())[1];
|
||||||
gpg(['--quick-add-key', fingerprint, 'cv25519', 'encr', 'never']);
|
gpg(['--quick-add-key', fingerprint, 'cv25519', 'encr', 'never']);
|
||||||
gpg(['--quick-add-key', fingerprint, 'ed25519', 'sign', 'never']);
|
gpg(['--quick-add-key', fingerprint, 'ed25519', 'sign', 'never']);
|
||||||
let data = null;
|
let data = null;
|
||||||
const keyStore = createKeyStore({ async load() { return data && JSON.parse(JSON.stringify(data)); }, async save(value) { data = JSON.parse(JSON.stringify(value)); } });
|
const keyStore = createKeyStore({ async load() { return data && JSON.parse(JSON.stringify(data)); }, async save(value) { data = JSON.parse(JSON.stringify(value)); } });
|
||||||
const mail = createPgpMail({ keyStore, cache: createPassphraseCache(async () => 10) });
|
const mail = createPgpMail({ keyStore, cache: createPassphraseCache(async () => 10) });
|
||||||
const { key } = await keyStore.generate({ name: 'Eppu Mail', email: 'eppu@example.com', passphrase: PASS });
|
const { key } = await keyStore.generate({ name: 'Eppu Mail', email: 'eppu@example.com', passphrase: PASS });
|
||||||
gpg(['--import'], Buffer.from(await keyStore.exportPublic(key.fingerprint)));
|
gpg(['--import'], Buffer.from(await keyStore.exportPublic(key.fingerprint)));
|
||||||
await keyStore.addContact({ armoredKey: gpg(['--armor', '--export', 'gina@example.com']).out.toString() });
|
await keyStore.addContact({ armoredKey: gpg(['--armor', '--export', 'gina@example.com']).out.toString() });
|
||||||
return { home, gpg, keyStore, mail };
|
return { home, gpg, keyStore, mail };
|
||||||
}
|
}
|
||||||
|
|
||||||
const options = extra => ({
|
const options = extra => ({
|
||||||
from: { name: 'Eppu Mail', address: 'eppu@example.com' }, to: 'Gina Gnu <gina@example.com>',
|
from: { name: 'Eppu Mail', address: 'eppu@example.com' }, to: 'Gina Gnu <gina@example.com>',
|
||||||
subject: 'Interop', text: 'Hello from ep-mail ✓', messageId: '<interop@ep-mail.local>', passphrase: PASS, ...extra
|
subject: 'Interop', text: 'Hello from ep-mail ✓', messageId: '<interop@ep-mail.local>', passphrase: PASS, ...extra
|
||||||
});
|
});
|
||||||
|
|
||||||
test('GnuPG decrypts and verifies mail encrypted and signed by ep-mail', { skip }, async () => {
|
test('GnuPG decrypts and verifies mail encrypted and signed by ep-mail', { skip }, async () => {
|
||||||
const { home, gpg, mail } = await setup();
|
const { home, gpg, mail } = await setup();
|
||||||
try {
|
try {
|
||||||
const { raw } = await mail.build(options({ encrypt: true, sign: true }));
|
const { raw } = await mail.build(options({ encrypt: true, sign: true }));
|
||||||
const parsed = await simpleParser(raw);
|
const parsed = await simpleParser(raw);
|
||||||
const armored = /-----BEGIN PGP MESSAGE-----[\s\S]+?-----END PGP MESSAGE-----/.exec(parsed.attachments[1]?.content?.toString() || parsed.attachments[0].content.toString())[0];
|
const armored = /-----BEGIN PGP MESSAGE-----[\s\S]+?-----END PGP MESSAGE-----/.exec(parsed.attachments[1]?.content?.toString() || parsed.attachments[0].content.toString())[0];
|
||||||
const { out, err } = gpg(['--decrypt'], Buffer.from(armored));
|
const { out, err } = gpg(['--decrypt'], Buffer.from(armored));
|
||||||
assert.match((await simpleParser(out)).text, /Hello from ep-mail ✓/);
|
assert.match((await simpleParser(out)).text, /Hello from ep-mail ✓/);
|
||||||
assert.match(err, /Good signature from "Eppu Mail <eppu@example.com>"/);
|
assert.match(err, /Good signature from "Eppu Mail <eppu@example.com>"/);
|
||||||
} finally { fs.rmSync(home, { recursive: true, force: true }); }
|
} finally { fs.rmSync(home, { recursive: true, force: true }); }
|
||||||
});
|
});
|
||||||
|
|
||||||
test('GnuPG verifies PGP/MIME signed-only mail from ep-mail', { skip }, async () => {
|
test('GnuPG verifies PGP/MIME signed-only mail from ep-mail', { skip }, async () => {
|
||||||
const { home, gpg, mail } = await setup();
|
const { home, gpg, mail } = await setup();
|
||||||
try {
|
try {
|
||||||
const { raw } = await mail.build(options({ sign: true }));
|
const { raw } = await mail.build(options({ sign: true }));
|
||||||
const text = raw.toString('latin1');
|
const text = raw.toString('latin1');
|
||||||
const { splitSigned } = require('../desktop/pgp-mail.cjs');
|
const { splitSigned } = require('../desktop/pgp-mail.cjs');
|
||||||
const boundary = /boundary="([^"]+)"/.exec(text)[1];
|
const boundary = /boundary="([^"]+)"/.exec(text)[1];
|
||||||
const parts = splitSigned(raw, boundary);
|
const parts = splitSigned(raw, boundary);
|
||||||
const signaturePath = path.join(home, 'sig.asc');
|
const signaturePath = path.join(home, 'sig.asc');
|
||||||
const dataPath = path.join(home, 'data.bin');
|
const dataPath = path.join(home, 'data.bin');
|
||||||
fs.writeFileSync(signaturePath, parts.signature);
|
fs.writeFileSync(signaturePath, parts.signature);
|
||||||
fs.writeFileSync(dataPath, parts.signed);
|
fs.writeFileSync(dataPath, parts.signed);
|
||||||
const { err } = gpg(['--verify', signaturePath, dataPath]);
|
const { err } = gpg(['--verify', signaturePath, dataPath]);
|
||||||
assert.match(err, /Good signature from "Eppu Mail/);
|
assert.match(err, /Good signature from "Eppu Mail/);
|
||||||
} finally { fs.rmSync(home, { recursive: true, force: true }); }
|
} finally { fs.rmSync(home, { recursive: true, force: true }); }
|
||||||
});
|
});
|
||||||
|
|
||||||
test('ep-mail decrypts GnuPG-encrypted PGP/MIME mail and verifies its signature', { skip }, async () => {
|
test('ep-mail decrypts GnuPG-encrypted PGP/MIME mail and verifies its signature', { skip }, async () => {
|
||||||
const { home, gpg, mail, keyStore } = await setup();
|
const { home, gpg, mail, keyStore } = await setup();
|
||||||
try {
|
try {
|
||||||
const inner = Buffer.from('Content-Type: text/plain; charset=utf-8\r\n\r\nHello from GnuPG ✓\r\n');
|
const inner = Buffer.from('Content-Type: text/plain; charset=utf-8\r\n\r\nHello from GnuPG ✓\r\n');
|
||||||
const armored = gpg(['--armor', '--encrypt', '--sign', '--local-user', 'gina@example.com', '--recipient', 'eppu@example.com'], inner).out.toString();
|
const armored = gpg(['--armor', '--encrypt', '--sign', '--local-user', 'gina@example.com', '--recipient', 'eppu@example.com'], inner).out.toString();
|
||||||
const source = Buffer.from(`From: Gina Gnu <gina@example.com>\r\nTo: eppu@example.com\r\nSubject: from gpg\r\nMIME-Version: 1.0\r\nContent-Type: multipart/encrypted; protocol="application/pgp-encrypted"; boundary="gb"\r\n\r\n--gb\r\nContent-Type: application/pgp-encrypted\r\n\r\nVersion: 1\r\n\r\n--gb\r\nContent-Type: application/octet-stream; name="encrypted.asc"\r\n\r\n${armored}\r\n--gb--\r\n`);
|
const source = Buffer.from(`From: Gina Gnu <gina@example.com>\r\nTo: eppu@example.com\r\nSubject: from gpg\r\nMIME-Version: 1.0\r\nContent-Type: multipart/encrypted; protocol="application/pgp-encrypted"; boundary="gb"\r\n\r\n--gb\r\nContent-Type: application/pgp-encrypted\r\n\r\nVersion: 1\r\n\r\n--gb\r\nContent-Type: application/octet-stream; name="encrypted.asc"\r\n\r\n${armored}\r\n--gb--\r\n`);
|
||||||
const result = await mail.decrypt(await simpleParser(source), { passphrase: PASS });
|
const result = await mail.decrypt(await simpleParser(source), { passphrase: PASS });
|
||||||
assert.match(result.parsed.text, /Hello from GnuPG ✓/);
|
assert.match(result.parsed.text, /Hello from GnuPG ✓/);
|
||||||
assert.equal(result.signatures[0].status, 'valid');
|
assert.equal(result.signatures[0].status, 'valid');
|
||||||
assert.equal(result.signatures[0].matchesSender, true);
|
assert.equal(result.signatures[0].matchesSender, true);
|
||||||
assert.ok(await keyStore.listContacts());
|
assert.ok(await keyStore.listContacts());
|
||||||
} finally { fs.rmSync(home, { recursive: true, force: true }); }
|
} finally { fs.rmSync(home, { recursive: true, force: true }); }
|
||||||
});
|
});
|
||||||
|
|
||||||
test('ep-mail decrypts GnuPG inline PGP and verifies GnuPG clear-signed and PGP/MIME signed mail', { skip }, async () => {
|
test('ep-mail decrypts GnuPG inline PGP and verifies GnuPG clear-signed and PGP/MIME signed mail', { skip }, async () => {
|
||||||
const { home, gpg, mail } = await setup();
|
const { home, gpg, mail } = await setup();
|
||||||
try {
|
try {
|
||||||
const inline = gpg(['--armor', '--encrypt', '--recipient', 'eppu@example.com'], Buffer.from('inline from gpg')).out.toString();
|
const inline = gpg(['--armor', '--encrypt', '--recipient', 'eppu@example.com'], Buffer.from('inline from gpg')).out.toString();
|
||||||
const inlineSource = Buffer.from(`From: gina@example.com\r\nSubject: i\r\nContent-Type: text/plain\r\n\r\n${inline}\r\n`);
|
const inlineSource = Buffer.from(`From: gina@example.com\r\nSubject: i\r\nContent-Type: text/plain\r\n\r\n${inline}\r\n`);
|
||||||
assert.match((await mail.decrypt(await simpleParser(inlineSource), { passphrase: PASS })).parsed.text, /inline from gpg/);
|
assert.match((await mail.decrypt(await simpleParser(inlineSource), { passphrase: PASS })).parsed.text, /inline from gpg/);
|
||||||
|
|
||||||
const clear = gpg(['--clearsign', '--local-user', 'gina@example.com'], Buffer.from('clear signed text\n')).out.toString().replace(/\r?\n/g, '\r\n');
|
const clear = gpg(['--clearsign', '--local-user', 'gina@example.com'], Buffer.from('clear signed text\n')).out.toString().replace(/\r?\n/g, '\r\n');
|
||||||
const clearSource = Buffer.from(`From: gina@example.com\r\nSubject: c\r\nContent-Type: text/plain\r\n\r\n${clear}\r\n`);
|
const clearSource = Buffer.from(`From: gina@example.com\r\nSubject: c\r\nContent-Type: text/plain\r\n\r\n${clear}\r\n`);
|
||||||
assert.equal((await mail.verifySigned(await simpleParser(clearSource), clearSource))[0].status, 'valid');
|
assert.equal((await mail.verifySigned(await simpleParser(clearSource), clearSource))[0].status, 'valid');
|
||||||
|
|
||||||
const signedPart = 'Content-Type: text/plain; charset=utf-8\r\n\r\nsigned by gpg';
|
const signedPart = 'Content-Type: text/plain; charset=utf-8\r\n\r\nsigned by gpg';
|
||||||
const detached = gpg(['--armor', '--detach-sign', '--local-user', 'gina@example.com'], Buffer.from(signedPart)).out.toString().replace(/\r?\n/g, '\r\n').trim();
|
const detached = gpg(['--armor', '--detach-sign', '--local-user', 'gina@example.com'], Buffer.from(signedPart)).out.toString().replace(/\r?\n/g, '\r\n').trim();
|
||||||
const mimeSource = Buffer.from(`From: gina@example.com\r\nSubject: m\r\nMIME-Version: 1.0\r\nContent-Type: multipart/signed; protocol="application/pgp-signature"; micalg=pgp-sha512; boundary="sb"\r\n\r\n--sb\r\n${signedPart}\r\n--sb\r\nContent-Type: application/pgp-signature\r\n\r\n${detached}\r\n--sb--\r\n`);
|
const mimeSource = Buffer.from(`From: gina@example.com\r\nSubject: m\r\nMIME-Version: 1.0\r\nContent-Type: multipart/signed; protocol="application/pgp-signature"; micalg=pgp-sha512; boundary="sb"\r\n\r\n--sb\r\n${signedPart}\r\n--sb\r\nContent-Type: application/pgp-signature\r\n\r\n${detached}\r\n--sb--\r\n`);
|
||||||
assert.equal((await mail.verifySigned(await simpleParser(mimeSource), mimeSource))[0].status, 'valid');
|
assert.equal((await mail.verifySigned(await simpleParser(mimeSource), mimeSource))[0].status, 'valid');
|
||||||
} finally { fs.rmSync(home, { recursive: true, force: true }); }
|
} finally { fs.rmSync(home, { recursive: true, force: true }); }
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,244 +1,244 @@
|
|||||||
const test = require('node:test');
|
const test = require('node:test');
|
||||||
const assert = require('node:assert/strict');
|
const assert = require('node:assert/strict');
|
||||||
const openpgp = require('openpgp');
|
const openpgp = require('openpgp');
|
||||||
const { createKeyServerService, listServers, normalizeCustomServer } = require('../desktop/pgp-keyservers.cjs');
|
const { createKeyServerService, listServers, normalizeCustomServer } = require('../desktop/pgp-keyservers.cjs');
|
||||||
const { createKeyStore } = require('../desktop/pgp-keystore.cjs');
|
const { createKeyStore } = require('../desktop/pgp-keystore.cjs');
|
||||||
|
|
||||||
const email = 'ada@example.org';
|
const email = 'ada@example.org';
|
||||||
|
|
||||||
function memoryStore() {
|
function memoryStore() {
|
||||||
let data = null;
|
let data = null;
|
||||||
return {
|
return {
|
||||||
async load() { return data && JSON.parse(JSON.stringify(data)); },
|
async load() { return data && JSON.parse(JSON.stringify(data)); },
|
||||||
async save(value) { data = JSON.parse(JSON.stringify(value)); }
|
async save(value) { data = JSON.parse(JSON.stringify(value)); }
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async function makeKey() {
|
async function makeKey() {
|
||||||
const generated = await openpgp.generateKey({
|
const generated = await openpgp.generateKey({
|
||||||
type: 'ecc',
|
type: 'ecc',
|
||||||
curve: 'curve25519Legacy',
|
curve: 'curve25519Legacy',
|
||||||
userIDs: [{ name: 'Ada Lovelace', email }],
|
userIDs: [{ name: 'Ada Lovelace', email }],
|
||||||
passphrase: 'correct horse battery',
|
passphrase: 'correct horse battery',
|
||||||
format: 'armored'
|
format: 'armored'
|
||||||
});
|
});
|
||||||
const key = await openpgp.readKey({ armoredKey: generated.publicKey });
|
const key = await openpgp.readKey({ armoredKey: generated.publicKey });
|
||||||
return { fingerprint: key.getFingerprint().toUpperCase(), armoredKey: key.armor() };
|
return { fingerprint: key.getFingerprint().toUpperCase(), armoredKey: key.armor() };
|
||||||
}
|
}
|
||||||
|
|
||||||
test('validates custom HTTPS key server configuration', () => {
|
test('validates custom HTTPS key server configuration', () => {
|
||||||
assert.deepEqual(normalizeCustomServer({
|
assert.deepEqual(normalizeCustomServer({
|
||||||
id: 'custom',
|
id: 'custom',
|
||||||
name: 'Internal server',
|
name: 'Internal server',
|
||||||
url: 'https://keys.example.org/openpgp',
|
url: 'https://keys.example.org/openpgp',
|
||||||
protocol: 'hkp'
|
protocol: 'hkp'
|
||||||
}), {
|
}), {
|
||||||
id: 'custom',
|
id: 'custom',
|
||||||
name: 'Internal server',
|
name: 'Internal server',
|
||||||
url: 'https://keys.example.org/openpgp/',
|
url: 'https://keys.example.org/openpgp/',
|
||||||
protocol: 'hkp',
|
protocol: 'hkp',
|
||||||
builtin: false
|
builtin: false
|
||||||
});
|
});
|
||||||
assert.throws(() => normalizeCustomServer({ name: 'Plain HTTP', url: 'http://keys.example.org', protocol: 'hkp' }), /HTTPS/);
|
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: '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: '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/);
|
assert.throws(() => normalizeCustomServer({ name: 'Unknown protocol', url: 'https://keys.example.org', protocol: 'unknown' }), /protocol/);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('all built-in and custom key servers start disabled', () => {
|
test('all built-in and custom key servers start disabled', () => {
|
||||||
const servers = listServers([{
|
const servers = listServers([{
|
||||||
id: 'custom',
|
id: 'custom',
|
||||||
name: 'Internal server',
|
name: 'Internal server',
|
||||||
url: 'https://keys.example.org',
|
url: 'https://keys.example.org',
|
||||||
protocol: 'hkp'
|
protocol: 'hkp'
|
||||||
}]);
|
}]);
|
||||||
assert.equal(servers.length, 3);
|
assert.equal(servers.length, 3);
|
||||||
assert.ok(servers.every(server => server.enabled === false));
|
assert.ok(servers.every(server => server.enabled === false));
|
||||||
const enabled = listServers([], ['openpgp-vks']);
|
const enabled = listServers([], ['openpgp-vks']);
|
||||||
assert.equal(enabled.find(server => server.id === 'openpgp-vks').enabled, true);
|
assert.equal(enabled.find(server => server.id === 'openpgp-vks').enabled, true);
|
||||||
assert.equal(enabled.find(server => server.id === 'mailvelope-hkp').enabled, false);
|
assert.equal(enabled.find(server => server.id === 'mailvelope-hkp').enabled, false);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('VKS lookup returns only valid keys matching the requested address', async () => {
|
test('VKS lookup returns only valid keys matching the requested address', async () => {
|
||||||
const key = await makeKey();
|
const key = await makeKey();
|
||||||
let requestedUrl;
|
let requestedUrl;
|
||||||
const service = createKeyServerService({
|
const service = createKeyServerService({
|
||||||
async fetchImpl(url, options) {
|
async fetchImpl(url, options) {
|
||||||
requestedUrl = new URL(url);
|
requestedUrl = new URL(url);
|
||||||
assert.equal(options.redirect, 'error');
|
assert.equal(options.redirect, 'error');
|
||||||
return new Response(key.armoredKey, { status: 200, headers: { 'content-type': 'application/pgp-keys' } });
|
return new Response(key.armoredKey, { status: 200, headers: { 'content-type': 'application/pgp-keys' } });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
const found = await service.lookup({
|
const found = await service.lookup({
|
||||||
id: 'openpgp-vks',
|
id: 'openpgp-vks',
|
||||||
name: 'keys.openpgp.org',
|
name: 'keys.openpgp.org',
|
||||||
url: 'https://keys.openpgp.org',
|
url: 'https://keys.openpgp.org',
|
||||||
protocol: 'vks'
|
protocol: 'vks'
|
||||||
}, email);
|
}, email);
|
||||||
assert.equal(requestedUrl.pathname, '/vks/v1/by-email/ada%40example.org');
|
assert.equal(requestedUrl.pathname, '/vks/v1/by-email/ada%40example.org');
|
||||||
assert.equal(found.length, 1);
|
assert.equal(found.length, 1);
|
||||||
assert.equal(found[0].fingerprint, key.fingerprint);
|
assert.equal(found[0].fingerprint, key.fingerprint);
|
||||||
assert.deepEqual(found[0].emails, [email]);
|
assert.deepEqual(found[0].emails, [email]);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('HKP lookup filters unrelated keys and reports an empty result', async () => {
|
test('HKP lookup filters unrelated keys and reports an empty result', async () => {
|
||||||
const key = await makeKey();
|
const key = await makeKey();
|
||||||
let requestedUrl;
|
let requestedUrl;
|
||||||
const service = createKeyServerService({
|
const service = createKeyServerService({
|
||||||
async fetchImpl(url) {
|
async fetchImpl(url) {
|
||||||
requestedUrl = new URL(url);
|
requestedUrl = new URL(url);
|
||||||
return new Response(`not a key\n${key.armoredKey}`, { status: 200 });
|
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 server = { id: 'custom', name: 'Example', url: 'https://keys.example.org/base/', protocol: 'hkp' };
|
||||||
const found = await service.lookup(server, email);
|
const found = await service.lookup(server, email);
|
||||||
assert.equal(requestedUrl.pathname, '/base/pks/lookup');
|
assert.equal(requestedUrl.pathname, '/base/pks/lookup');
|
||||||
assert.equal(requestedUrl.searchParams.get('op'), 'get');
|
assert.equal(requestedUrl.searchParams.get('op'), 'get');
|
||||||
assert.equal(requestedUrl.searchParams.get('search'), email);
|
assert.equal(requestedUrl.searchParams.get('search'), email);
|
||||||
assert.equal(found.length, 1);
|
assert.equal(found.length, 1);
|
||||||
assert.deepEqual(await service.lookup(server, 'other@example.org'), []);
|
assert.deepEqual(await service.lookup(server, 'other@example.org'), []);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('enabled-server lookup checks every enabled server, merges duplicate keys and reports failures', async () => {
|
test('enabled-server lookup checks every enabled server, merges duplicate keys and reports failures', async () => {
|
||||||
const key = await makeKey();
|
const key = await makeKey();
|
||||||
const requested = [];
|
const requested = [];
|
||||||
const service = createKeyServerService({
|
const service = createKeyServerService({
|
||||||
async fetchImpl(url) {
|
async fetchImpl(url) {
|
||||||
const target = new URL(url);
|
const target = new URL(url);
|
||||||
requested.push(target.hostname);
|
requested.push(target.hostname);
|
||||||
if (target.hostname === 'broken.example.org') throw new Error('server unavailable');
|
if (target.hostname === 'broken.example.org') throw new Error('server unavailable');
|
||||||
return new Response(key.armoredKey, { status: 200 });
|
return new Response(key.armoredKey, { status: 200 });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
const results = await service.lookupEnabled([
|
const results = await service.lookupEnabled([
|
||||||
{ id: 'one', name: 'First', url: 'https://first.example.org', protocol: 'hkp', enabled: true },
|
{ 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: '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: '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 }
|
{ id: 'off', name: 'Disabled', url: 'https://disabled.example.org', protocol: 'hkp', enabled: false }
|
||||||
], email);
|
], email);
|
||||||
assert.deepEqual(requested.sort(), ['broken.example.org', 'first.example.org', 'second.example.org']);
|
assert.deepEqual(requested.sort(), ['broken.example.org', 'first.example.org', 'second.example.org']);
|
||||||
assert.equal(results.keys.length, 1);
|
assert.equal(results.keys.length, 1);
|
||||||
assert.deepEqual(results.keys[0].sources, ['First', 'Second']);
|
assert.deepEqual(results.keys[0].sources, ['First', 'Second']);
|
||||||
assert.deepEqual(results.errors.map(error => error.name), ['Offline']);
|
assert.deepEqual(results.errors.map(error => error.name), ['Offline']);
|
||||||
assert.deepEqual(results.searchedServers.map(server => server.name), ['First', 'Second', 'Offline']);
|
assert.deepEqual(results.searchedServers.map(server => server.name), ['First', 'Second', 'Offline']);
|
||||||
await assert.rejects(() => service.lookupEnabled([
|
await assert.rejects(() => service.lookupEnabled([
|
||||||
{ id: 'off', name: 'Disabled', url: 'https://disabled.example.org', protocol: 'hkp', enabled: false }
|
{ id: 'off', name: 'Disabled', url: 'https://disabled.example.org', protocol: 'hkp', enabled: false }
|
||||||
], email), /Enable at least one key server/);
|
], email), /Enable at least one key server/);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('VKS publication uploads only the public key and requests email verification', async () => {
|
test('VKS publication uploads only the public key and requests email verification', async () => {
|
||||||
const key = await makeKey();
|
const key = await makeKey();
|
||||||
const calls = [];
|
const calls = [];
|
||||||
const service = createKeyServerService({
|
const service = createKeyServerService({
|
||||||
async fetchImpl(url, options) {
|
async fetchImpl(url, options) {
|
||||||
calls.push({ url: new URL(url), options });
|
calls.push({ url: new URL(url), options });
|
||||||
if (calls.length === 1) {
|
if (calls.length === 1) {
|
||||||
return Response.json({
|
return Response.json({
|
||||||
key_fpr: key.fingerprint,
|
key_fpr: key.fingerprint,
|
||||||
token: 'temporary-upload-token',
|
token: 'temporary-upload-token',
|
||||||
status: { [email]: 'unpublished' }
|
status: { [email]: 'unpublished' }
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
return Response.json({ key_fpr: key.fingerprint, token: 'temporary-upload-token', status: { [email]: 'pending' } });
|
return Response.json({ key_fpr: key.fingerprint, token: 'temporary-upload-token', status: { [email]: 'pending' } });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
const result = await service.publish({
|
const result = await service.publish({
|
||||||
id: 'openpgp-vks',
|
id: 'openpgp-vks',
|
||||||
name: 'keys.openpgp.org',
|
name: 'keys.openpgp.org',
|
||||||
url: 'https://keys.openpgp.org',
|
url: 'https://keys.openpgp.org',
|
||||||
protocol: 'vks'
|
protocol: 'vks'
|
||||||
}, email, key.armoredKey, key.fingerprint);
|
}, email, key.armoredKey, key.fingerprint);
|
||||||
assert.equal(calls[0].url.pathname, '/vks/v1/upload');
|
assert.equal(calls[0].url.pathname, '/vks/v1/upload');
|
||||||
assert.equal(calls[1].url.pathname, '/vks/v1/request-verify');
|
assert.equal(calls[1].url.pathname, '/vks/v1/request-verify');
|
||||||
assert.equal(result.verification, 'pending');
|
assert.equal(result.verification, 'pending');
|
||||||
const upload = JSON.parse(calls[0].options.body);
|
const upload = JSON.parse(calls[0].options.body);
|
||||||
assert.equal(upload.keytext, key.armoredKey);
|
assert.equal(upload.keytext, key.armoredKey);
|
||||||
assert.equal(upload.keytext.includes('PRIVATE KEY'), false);
|
assert.equal(upload.keytext.includes('PRIVATE KEY'), false);
|
||||||
assert.deepEqual(JSON.parse(calls[1].options.body).addresses, [email]);
|
assert.deepEqual(JSON.parse(calls[1].options.body).addresses, [email]);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('HKP publication posts armored public material only', async () => {
|
test('HKP publication posts armored public material only', async () => {
|
||||||
const key = await makeKey();
|
const key = await makeKey();
|
||||||
let requestInfo;
|
let requestInfo;
|
||||||
const service = createKeyServerService({
|
const service = createKeyServerService({
|
||||||
async fetchImpl(url, options) {
|
async fetchImpl(url, options) {
|
||||||
requestInfo = { url: new URL(url), options };
|
requestInfo = { url: new URL(url), options };
|
||||||
return new Response('Upload successful. Check your inbox to verify your email address.', { status: 200 });
|
return new Response('Upload successful. Check your inbox to verify your email address.', { status: 200 });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
const result = await service.publish({
|
const result = await service.publish({
|
||||||
id: 'mailvelope-hkp',
|
id: 'mailvelope-hkp',
|
||||||
name: 'keys.mailvelope.com',
|
name: 'keys.mailvelope.com',
|
||||||
url: 'https://keys.mailvelope.com',
|
url: 'https://keys.mailvelope.com',
|
||||||
protocol: 'hkp'
|
protocol: 'hkp'
|
||||||
}, email, key.armoredKey, key.fingerprint);
|
}, email, key.armoredKey, key.fingerprint);
|
||||||
assert.equal(requestInfo.url.pathname, '/pks/add');
|
assert.equal(requestInfo.url.pathname, '/pks/add');
|
||||||
assert.equal(requestInfo.options.headers['content-type'], 'application/x-www-form-urlencoded');
|
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(new URLSearchParams(requestInfo.options.body).get('keytext'), key.armoredKey);
|
||||||
assert.equal(requestInfo.options.body.includes('PRIVATE KEY'), false);
|
assert.equal(requestInfo.options.body.includes('PRIVATE KEY'), false);
|
||||||
assert.equal(result.verification, 'check-email');
|
assert.equal(result.verification, 'check-email');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('key-server contact imports stay untrusted and retain keyserver provenance', async () => {
|
test('key-server contact imports stay untrusted and retain keyserver provenance', async () => {
|
||||||
const key = await makeKey();
|
const key = await makeKey();
|
||||||
const keyStore = createKeyStore(memoryStore());
|
const keyStore = createKeyStore(memoryStore());
|
||||||
const added = await keyStore.addContact({ armoredKey: key.armoredKey, source: 'keyserver' });
|
const added = await keyStore.addContact({ armoredKey: key.armoredKey, source: 'keyserver' });
|
||||||
assert.equal(added.contact.trust, 'unknown');
|
assert.equal(added.contact.trust, 'unknown');
|
||||||
assert.equal(added.contact.source, 'keyserver');
|
assert.equal(added.contact.source, 'keyserver');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('lookup rejects oversized responses and HTTP failures', async () => {
|
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 server = { id: 'openpgp-vks', name: 'keys.openpgp.org', url: 'https://keys.openpgp.org', protocol: 'vks' };
|
||||||
const tooLarge = createKeyServerService({
|
const tooLarge = createKeyServerService({
|
||||||
async fetchImpl() { return new Response('x'.repeat(600001), { status: 200 }); }
|
async fetchImpl() { return new Response('x'.repeat(600001), { status: 200 }); }
|
||||||
});
|
});
|
||||||
await assert.rejects(() => tooLarge.lookup(server, email), /too large/);
|
await assert.rejects(() => tooLarge.lookup(server, email), /too large/);
|
||||||
const failure = createKeyServerService({
|
const failure = createKeyServerService({
|
||||||
async fetchImpl() { return new Response('', { status: 503 }); }
|
async fetchImpl() { return new Response('', { status: 503 }); }
|
||||||
});
|
});
|
||||||
await assert.rejects(() => failure.lookup(server, email), /HTTP 503/);
|
await assert.rejects(() => failure.lookup(server, email), /HTTP 503/);
|
||||||
const invalid = createKeyServerService({
|
const invalid = createKeyServerService({
|
||||||
async fetchImpl() { return new Response('<html>unexpected response</html>', { status: 200 }); }
|
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/);
|
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 () => {
|
test('VKS verification failure reports that the key upload already succeeded', async () => {
|
||||||
const key = await makeKey();
|
const key = await makeKey();
|
||||||
let calls = 0;
|
let calls = 0;
|
||||||
const service = createKeyServerService({
|
const service = createKeyServerService({
|
||||||
async fetchImpl() {
|
async fetchImpl() {
|
||||||
calls += 1;
|
calls += 1;
|
||||||
if (calls === 1) {
|
if (calls === 1) {
|
||||||
return Response.json({
|
return Response.json({
|
||||||
key_fpr: key.fingerprint,
|
key_fpr: key.fingerprint,
|
||||||
token: 'temporary-upload-token',
|
token: 'temporary-upload-token',
|
||||||
status: { [email]: 'unpublished' }
|
status: { [email]: 'unpublished' }
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
throw new Error('network unavailable');
|
throw new Error('network unavailable');
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
const result = await service.publish({
|
const result = await service.publish({
|
||||||
id: 'openpgp-vks',
|
id: 'openpgp-vks',
|
||||||
name: 'keys.openpgp.org',
|
name: 'keys.openpgp.org',
|
||||||
url: 'https://keys.openpgp.org',
|
url: 'https://keys.openpgp.org',
|
||||||
protocol: 'vks'
|
protocol: 'vks'
|
||||||
}, email, key.armoredKey, key.fingerprint);
|
}, email, key.armoredKey, key.fingerprint);
|
||||||
assert.equal(result.uploaded, true);
|
assert.equal(result.uploaded, true);
|
||||||
assert.equal(result.verification, 'request-failed');
|
assert.equal(result.verification, 'request-failed');
|
||||||
assert.match(result.warning, /key was uploaded/);
|
assert.match(result.warning, /key was uploaded/);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('publication rejects a fingerprint that does not match the public key', async () => {
|
test('publication rejects a fingerprint that does not match the public key', async () => {
|
||||||
const key = await makeKey();
|
const key = await makeKey();
|
||||||
const service = createKeyServerService({
|
const service = createKeyServerService({
|
||||||
async fetchImpl() { throw new Error('unexpected network request'); }
|
async fetchImpl() { throw new Error('unexpected network request'); }
|
||||||
});
|
});
|
||||||
await assert.rejects(() => service.publish({
|
await assert.rejects(() => service.publish({
|
||||||
id: 'mailvelope-hkp',
|
id: 'mailvelope-hkp',
|
||||||
name: 'keys.mailvelope.com',
|
name: 'keys.mailvelope.com',
|
||||||
url: 'https://keys.mailvelope.com',
|
url: 'https://keys.mailvelope.com',
|
||||||
protocol: 'hkp'
|
protocol: 'hkp'
|
||||||
}, email, key.armoredKey, '0'.repeat(40)), /does not match/);
|
}, email, key.armoredKey, '0'.repeat(40)), /does not match/);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,123 +1,123 @@
|
|||||||
const test = require('node:test');
|
const test = require('node:test');
|
||||||
const assert = require('node:assert/strict');
|
const assert = require('node:assert/strict');
|
||||||
const openpgp = require('openpgp');
|
const openpgp = require('openpgp');
|
||||||
const { createKeyStore } = require('../desktop/pgp-keystore.cjs');
|
const { createKeyStore } = require('../desktop/pgp-keystore.cjs');
|
||||||
|
|
||||||
function memoryStore() {
|
function memoryStore() {
|
||||||
let data = null;
|
let data = null;
|
||||||
return { load: async () => data, save: async value => { data = JSON.parse(JSON.stringify(value)); } };
|
return { load: async () => data, save: async value => { data = JSON.parse(JSON.stringify(value)); } };
|
||||||
}
|
}
|
||||||
|
|
||||||
const passphrase = 'correct horse battery';
|
const passphrase = 'correct horse battery';
|
||||||
|
|
||||||
test('generates a passphrase-protected key and never lists secrets', async () => {
|
test('generates a passphrase-protected key and never lists secrets', async () => {
|
||||||
const storage = memoryStore();
|
const storage = memoryStore();
|
||||||
const keys = createKeyStore(storage);
|
const keys = createKeyStore(storage);
|
||||||
const { key, revocationCertificate } = await keys.generate({ name: 'Ada', email: 'ada@example.com', passphrase });
|
const { key, revocationCertificate } = await keys.generate({ name: 'Ada', email: 'ada@example.com', passphrase });
|
||||||
assert.match(key.fingerprint, /^[0-9A-F]{40,64}$/);
|
assert.match(key.fingerprint, /^[0-9A-F]{40,64}$/);
|
||||||
assert.ok(revocationCertificate.includes('BEGIN PGP PUBLIC KEY BLOCK'));
|
assert.ok(revocationCertificate.includes('BEGIN PGP PUBLIC KEY BLOCK'));
|
||||||
const listed = await keys.list();
|
const listed = await keys.list();
|
||||||
assert.equal(listed.length, 1);
|
assert.equal(listed.length, 1);
|
||||||
assert.equal(JSON.stringify(listed).includes('PRIVATE'), false);
|
assert.equal(JSON.stringify(listed).includes('PRIVATE'), false);
|
||||||
const stored = (await storage.load()).keys[0];
|
const stored = (await storage.load()).keys[0];
|
||||||
const parsed = await openpgp.readPrivateKey({ armoredKey: stored.privateKey });
|
const parsed = await openpgp.readPrivateKey({ armoredKey: stored.privateKey });
|
||||||
assert.equal(parsed.isDecrypted(), false);
|
assert.equal(parsed.isDecrypted(), false);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('rejects weak passphrases and bad addresses', async () => {
|
test('rejects weak passphrases and bad addresses', async () => {
|
||||||
const keys = createKeyStore(memoryStore());
|
const keys = createKeyStore(memoryStore());
|
||||||
await assert.rejects(keys.generate({ name: 'A', email: 'a@example.com', passphrase: 'short' }), /at least 8/);
|
await assert.rejects(keys.generate({ name: 'A', email: 'a@example.com', passphrase: 'short' }), /at least 8/);
|
||||||
await assert.rejects(keys.generate({ name: 'A', email: 'nope', passphrase }), /valid email/);
|
await assert.rejects(keys.generate({ name: 'A', email: 'nope', passphrase }), /valid email/);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('export requires the right passphrase and round-trips through import', async () => {
|
test('export requires the right passphrase and round-trips through import', async () => {
|
||||||
const first = createKeyStore(memoryStore());
|
const first = createKeyStore(memoryStore());
|
||||||
const { key } = await first.generate({ name: 'Ada', email: 'ada@example.com', passphrase });
|
const { key } = await first.generate({ name: 'Ada', email: 'ada@example.com', passphrase });
|
||||||
await assert.rejects(first.exportPrivate(key.fingerprint, 'wrong passphrase'), /incorrect/);
|
await assert.rejects(first.exportPrivate(key.fingerprint, 'wrong passphrase'), /incorrect/);
|
||||||
const armored = await first.exportPrivate(key.fingerprint, passphrase);
|
const armored = await first.exportPrivate(key.fingerprint, passphrase);
|
||||||
const second = createKeyStore(memoryStore());
|
const second = createKeyStore(memoryStore());
|
||||||
const imported = await second.import({ armoredKey: armored, passphrase });
|
const imported = await second.import({ armoredKey: armored, passphrase });
|
||||||
assert.equal(imported.fingerprint, key.fingerprint);
|
assert.equal(imported.fingerprint, key.fingerprint);
|
||||||
assert.equal(imported.email, 'ada@example.com');
|
assert.equal(imported.email, 'ada@example.com');
|
||||||
await assert.rejects(second.import({ armoredKey: armored, passphrase }), /already/);
|
await assert.rejects(second.import({ armoredKey: armored, passphrase }), /already/);
|
||||||
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 () => {
|
test('changes a key passphrase without changing its public identity or revocation certificate', async () => {
|
||||||
const storage = memoryStore();
|
const storage = memoryStore();
|
||||||
const keys = createKeyStore(storage);
|
const keys = createKeyStore(storage);
|
||||||
const { key, revocationCertificate } = await keys.generate({ name: 'Ada', email: 'ada@example.com', passphrase });
|
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 original = JSON.parse(JSON.stringify((await storage.load()).keys[0]));
|
||||||
const newPassphrase = 'new passphrase securely';
|
const newPassphrase = 'new passphrase securely';
|
||||||
|
|
||||||
await assert.rejects(keys.changePassphrase(key.fingerprint, 'wrong passphrase', newPassphrase), /incorrect/);
|
await assert.rejects(keys.changePassphrase(key.fingerprint, 'wrong passphrase', newPassphrase), /incorrect/);
|
||||||
await assert.rejects(keys.changePassphrase(key.fingerprint, passphrase, 'short'), /at least 8/);
|
await assert.rejects(keys.changePassphrase(key.fingerprint, passphrase, 'short'), /at least 8/);
|
||||||
assert.deepEqual((await storage.load()).keys[0], original);
|
assert.deepEqual((await storage.load()).keys[0], original);
|
||||||
|
|
||||||
assert.deepEqual(await keys.changePassphrase(key.fingerprint, passphrase, newPassphrase), { changed: true });
|
assert.deepEqual(await keys.changePassphrase(key.fingerprint, passphrase, newPassphrase), { changed: true });
|
||||||
const changed = (await storage.load()).keys[0];
|
const changed = (await storage.load()).keys[0];
|
||||||
assert.equal(changed.fingerprint, original.fingerprint);
|
assert.equal(changed.fingerprint, original.fingerprint);
|
||||||
assert.equal(changed.publicKey, original.publicKey);
|
assert.equal(changed.publicKey, original.publicKey);
|
||||||
assert.equal(changed.name, original.name);
|
assert.equal(changed.name, original.name);
|
||||||
assert.equal(changed.email, original.email);
|
assert.equal(changed.email, original.email);
|
||||||
assert.equal(changed.accountId, original.accountId);
|
assert.equal(changed.accountId, original.accountId);
|
||||||
assert.equal(changed.createdAt, original.createdAt);
|
assert.equal(changed.createdAt, original.createdAt);
|
||||||
assert.equal(changed.algorithm, original.algorithm);
|
assert.equal(changed.algorithm, original.algorithm);
|
||||||
assert.equal(changed.revocationCertificate, original.revocationCertificate);
|
assert.equal(changed.revocationCertificate, original.revocationCertificate);
|
||||||
assert.notEqual(changed.privateKey, original.privateKey);
|
assert.notEqual(changed.privateKey, original.privateKey);
|
||||||
await assert.rejects(keys.exportPrivate(key.fingerprint, passphrase), /incorrect/);
|
await assert.rejects(keys.exportPrivate(key.fingerprint, passphrase), /incorrect/);
|
||||||
assert.equal(await keys.exportPrivate(key.fingerprint, newPassphrase), changed.privateKey);
|
assert.equal(await keys.exportPrivate(key.fingerprint, newPassphrase), changed.privateKey);
|
||||||
assert.equal(await keys.exportRevocation(key.fingerprint, newPassphrase), revocationCertificate);
|
assert.equal(await keys.exportRevocation(key.fingerprint, newPassphrase), revocationCertificate);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('does not mutate the loaded key if saving a changed passphrase fails', async () => {
|
test('does not mutate the loaded key if saving a changed passphrase fails', async () => {
|
||||||
let data = null;
|
let data = null;
|
||||||
let failSave = false;
|
let failSave = false;
|
||||||
const storage = {
|
const storage = {
|
||||||
load: async () => data,
|
load: async () => data,
|
||||||
save: async value => {
|
save: async value => {
|
||||||
if (failSave) throw new Error('Storage unavailable.');
|
if (failSave) throw new Error('Storage unavailable.');
|
||||||
data = JSON.parse(JSON.stringify(value));
|
data = JSON.parse(JSON.stringify(value));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
const keys = createKeyStore(storage);
|
const keys = createKeyStore(storage);
|
||||||
const { key } = await keys.generate({ name: 'Ada', email: 'ada@example.com', passphrase });
|
const { key } = await keys.generate({ name: 'Ada', email: 'ada@example.com', passphrase });
|
||||||
const original = JSON.parse(JSON.stringify(data.keys[0]));
|
const original = JSON.parse(JSON.stringify(data.keys[0]));
|
||||||
failSave = true;
|
failSave = true;
|
||||||
|
|
||||||
await assert.rejects(keys.changePassphrase(key.fingerprint, passphrase, 'new passphrase securely'), /Storage unavailable/);
|
await assert.rejects(keys.changePassphrase(key.fingerprint, passphrase, 'new passphrase securely'), /Storage unavailable/);
|
||||||
assert.deepEqual(data.keys[0], original);
|
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());
|
||||||
const imported = await keys.import({ armoredKey: privateKey, passphrase });
|
const imported = await keys.import({ armoredKey: privateKey, passphrase });
|
||||||
const exported = await keys.exportPrivate(imported.fingerprint, passphrase);
|
const exported = await keys.exportPrivate(imported.fingerprint, passphrase);
|
||||||
assert.equal((await openpgp.readPrivateKey({ armoredKey: exported })).isDecrypted(), false);
|
assert.equal((await openpgp.readPrivateKey({ armoredKey: exported })).isDecrypted(), false);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('rejects invalid key material and a wrong passphrase on import', async () => {
|
test('rejects invalid key material and a wrong passphrase on import', async () => {
|
||||||
const keys = createKeyStore(memoryStore());
|
const keys = createKeyStore(memoryStore());
|
||||||
await assert.rejects(keys.import({ armoredKey: 'not a key', passphrase }), /valid OpenPGP/);
|
await assert.rejects(keys.import({ armoredKey: 'not a key', passphrase }), /valid OpenPGP/);
|
||||||
const source = createKeyStore(memoryStore());
|
const source = createKeyStore(memoryStore());
|
||||||
const { key } = await source.generate({ name: 'C', email: 'c@example.com', passphrase });
|
const { key } = await source.generate({ name: 'C', email: 'c@example.com', passphrase });
|
||||||
const armored = await source.exportPrivate(key.fingerprint, passphrase);
|
const armored = await source.exportPrivate(key.fingerprint, passphrase);
|
||||||
await assert.rejects(keys.import({ armoredKey: armored, passphrase: 'another passphrase' }), /incorrect/);
|
await assert.rejects(keys.import({ armoredKey: armored, passphrase: 'another passphrase' }), /incorrect/);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('deleting a key needs the passphrase', async () => {
|
test('deleting a key needs the passphrase', async () => {
|
||||||
const keys = createKeyStore(memoryStore());
|
const keys = createKeyStore(memoryStore());
|
||||||
const { key } = await keys.generate({ name: 'D', email: 'd@example.com', passphrase });
|
const { key } = await keys.generate({ name: 'D', email: 'd@example.com', passphrase });
|
||||||
await assert.rejects(keys.remove(key.fingerprint, 'wrong passphrase'), /incorrect/);
|
await assert.rejects(keys.remove(key.fingerprint, 'wrong passphrase'), /incorrect/);
|
||||||
assert.equal((await keys.list()).length, 1);
|
assert.equal((await keys.list()).length, 1);
|
||||||
await keys.remove(key.fingerprint, passphrase);
|
await keys.remove(key.fingerprint, passphrase);
|
||||||
assert.equal((await keys.list()).length, 0);
|
assert.equal((await keys.list()).length, 0);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('stored revocation certificate is returned only after unlocking', async () => {
|
test('stored revocation certificate is returned only after unlocking', async () => {
|
||||||
const keys = createKeyStore(memoryStore());
|
const keys = createKeyStore(memoryStore());
|
||||||
const { key } = await keys.generate({ name: 'E', email: 'e@example.com', passphrase });
|
const { key } = await keys.generate({ name: 'E', email: 'e@example.com', passphrase });
|
||||||
await assert.rejects(keys.exportRevocation(key.fingerprint, 'wrong passphrase'), /incorrect/);
|
await assert.rejects(keys.exportRevocation(key.fingerprint, 'wrong passphrase'), /incorrect/);
|
||||||
assert.ok((await keys.exportRevocation(key.fingerprint, passphrase)).includes('BEGIN PGP PUBLIC KEY BLOCK'));
|
assert.ok((await keys.exportRevocation(key.fingerprint, passphrase)).includes('BEGIN PGP PUBLIC KEY BLOCK'));
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,216 +1,216 @@
|
|||||||
const test = require('node:test');
|
const test = require('node:test');
|
||||||
const assert = require('node:assert/strict');
|
const assert = require('node:assert/strict');
|
||||||
const openpgp = require('openpgp');
|
const openpgp = require('openpgp');
|
||||||
const MailComposer = require('nodemailer/lib/mail-composer');
|
const MailComposer = require('nodemailer/lib/mail-composer');
|
||||||
const { simpleParser } = require('mailparser');
|
const { simpleParser } = require('mailparser');
|
||||||
const { createKeyStore } = require('../desktop/pgp-keystore.cjs');
|
const { createKeyStore } = require('../desktop/pgp-keystore.cjs');
|
||||||
const { createPgpMail, createPassphraseCache, detect } = require('../desktop/pgp-mail.cjs');
|
const { createPgpMail, createPassphraseCache, detect } = require('../desktop/pgp-mail.cjs');
|
||||||
|
|
||||||
function memoryStore() {
|
function memoryStore() {
|
||||||
let data = null;
|
let data = null;
|
||||||
return { async load() { return data && JSON.parse(JSON.stringify(data)); }, async save(value) { data = JSON.parse(JSON.stringify(value)); } };
|
return { async load() { return data && JSON.parse(JSON.stringify(data)); }, async save(value) { data = JSON.parse(JSON.stringify(value)); } };
|
||||||
}
|
}
|
||||||
|
|
||||||
async function actor(name, email, passphrase = 'correct horse') {
|
async function actor(name, email, passphrase = 'correct horse') {
|
||||||
const keyStore = createKeyStore(memoryStore());
|
const keyStore = createKeyStore(memoryStore());
|
||||||
const cache = createPassphraseCache(async () => 10);
|
const cache = createPassphraseCache(async () => 10);
|
||||||
const mail = createPgpMail({ keyStore, cache });
|
const mail = createPgpMail({ keyStore, cache });
|
||||||
const { key } = await keyStore.generate({ name, email, passphrase });
|
const { key } = await keyStore.generate({ name, email, passphrase });
|
||||||
return { keyStore, cache, mail, key, email, passphrase, name };
|
return { keyStore, cache, mail, key, email, passphrase, name };
|
||||||
}
|
}
|
||||||
|
|
||||||
async function exchange(a, b) {
|
async function exchange(a, b) {
|
||||||
await a.keyStore.addContact({ armoredKey: await b.keyStore.exportPublic(b.key.fingerprint) });
|
await a.keyStore.addContact({ armoredKey: await b.keyStore.exportPublic(b.key.fingerprint) });
|
||||||
await b.keyStore.addContact({ armoredKey: await a.keyStore.exportPublic(a.key.fingerprint) });
|
await b.keyStore.addContact({ armoredKey: await a.keyStore.exportPublic(a.key.fingerprint) });
|
||||||
}
|
}
|
||||||
|
|
||||||
const sendOptions = (from, to, extra = {}) => ({
|
const sendOptions = (from, to, extra = {}) => ({
|
||||||
from: { name: from.name, address: from.email }, to, subject: 'Héllo secrèt', text: 'Top secret ✓\nline two', messageId: '<abc@ep-mail.local>', ...extra
|
from: { name: from.name, address: from.email }, to, subject: 'Héllo secrèt', text: 'Top secret ✓\nline two', messageId: '<abc@ep-mail.local>', ...extra
|
||||||
});
|
});
|
||||||
|
|
||||||
test('encrypts and signs for a recipient and the sender can read the copy', async () => {
|
test('encrypts and signs for a recipient and the sender can read the copy', 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 exchange(alice, bob);
|
await exchange(alice, bob);
|
||||||
const { raw, envelope } = await alice.mail.build(sendOptions(alice, 'Bob <bob@example.com>', { encrypt: true, sign: true, passphrase: alice.passphrase }));
|
const { raw, envelope } = await alice.mail.build(sendOptions(alice, 'Bob <bob@example.com>', { encrypt: true, sign: true, passphrase: alice.passphrase }));
|
||||||
assert.deepEqual(envelope.to, ['bob@example.com']);
|
assert.deepEqual(envelope.to, ['bob@example.com']);
|
||||||
assert.ok(!raw.toString('latin1').includes('Top secret'));
|
assert.ok(!raw.toString('latin1').includes('Top secret'));
|
||||||
const parsed = await simpleParser(raw);
|
const parsed = await simpleParser(raw);
|
||||||
assert.equal(parsed.subject, 'Héllo secrèt');
|
assert.equal(parsed.subject, 'Héllo secrèt');
|
||||||
assert.equal(detect(parsed), 'encrypted-mime');
|
assert.equal(detect(parsed), 'encrypted-mime');
|
||||||
await assert.rejects(() => bob.mail.decrypt(parsed), error => error.code === 'PASSPHRASE_REQUIRED');
|
await assert.rejects(() => bob.mail.decrypt(parsed), error => error.code === 'PASSPHRASE_REQUIRED');
|
||||||
await assert.rejects(() => bob.mail.decrypt(parsed, { passphrase: 'wrong wrong' }), error => error.code === 'BAD_PASSPHRASE');
|
await assert.rejects(() => bob.mail.decrypt(parsed, { passphrase: 'wrong wrong' }), error => error.code === 'BAD_PASSPHRASE');
|
||||||
const result = await bob.mail.decrypt(parsed, { passphrase: bob.passphrase });
|
const result = await bob.mail.decrypt(parsed, { passphrase: bob.passphrase });
|
||||||
assert.equal(result.parsed.text.trim(), 'Top secret ✓\nline two');
|
assert.equal(result.parsed.text.trim(), 'Top secret ✓\nline two');
|
||||||
assert.equal(result.signatures[0].status, 'valid');
|
assert.equal(result.signatures[0].status, 'valid');
|
||||||
assert.equal(result.signatures[0].matchesSender, true);
|
assert.equal(result.signatures[0].matchesSender, true);
|
||||||
const again = await bob.mail.decrypt(await simpleParser(raw));
|
const again = await bob.mail.decrypt(await simpleParser(raw));
|
||||||
assert.equal(again.signatures.length, 1);
|
assert.equal(again.signatures.length, 1);
|
||||||
const own = await alice.mail.decrypt(parsed, { passphrase: alice.passphrase });
|
const own = await alice.mail.decrypt(parsed, { passphrase: alice.passphrase });
|
||||||
assert.match(own.parsed.text, /Top secret/);
|
assert.match(own.parsed.text, /Top secret/);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('refuses to encrypt without a recipient key instead of downgrading', async () => {
|
test('refuses to encrypt without a recipient key instead of downgrading', async () => {
|
||||||
const alice = await actor('Alice', 'alice@example.com');
|
const alice = await actor('Alice', 'alice@example.com');
|
||||||
await assert.rejects(
|
await assert.rejects(
|
||||||
() => alice.mail.build(sendOptions(alice, 'carol@example.com', { encrypt: true })),
|
() => alice.mail.build(sendOptions(alice, 'carol@example.com', { encrypt: true })),
|
||||||
error => error.code === 'NO_RECIPIENT_KEY' && error.details.missing[0] === 'carol@example.com'
|
error => error.code === 'NO_RECIPIENT_KEY' && error.details.missing[0] === 'carol@example.com'
|
||||||
);
|
);
|
||||||
const status = await alice.mail.recipientStatus(['carol@example.com'], { sign: true, from: 'alice@example.com' });
|
const status = await alice.mail.recipientStatus(['carol@example.com'], { sign: true, from: 'alice@example.com' });
|
||||||
assert.deepEqual(status.missing, ['carol@example.com']);
|
assert.deepEqual(status.missing, ['carol@example.com']);
|
||||||
assert.equal(status.signer.email, 'alice@example.com');
|
assert.equal(status.signer.email, 'alice@example.com');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('encrypts to several recipients and each can decrypt', async () => {
|
test('encrypts to several recipients and each can decrypt', 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');
|
||||||
const carol = await actor('Carol', 'carol@example.com');
|
const carol = await actor('Carol', 'carol@example.com');
|
||||||
for (const other of [bob, carol]) await alice.keyStore.addContact({ armoredKey: await other.keyStore.exportPublic(other.key.fingerprint) });
|
for (const other of [bob, carol]) await alice.keyStore.addContact({ armoredKey: await other.keyStore.exportPublic(other.key.fingerprint) });
|
||||||
const { raw } = await alice.mail.build(sendOptions(alice, 'bob@example.com', { cc: 'carol@example.com', encrypt: true }));
|
const { raw } = await alice.mail.build(sendOptions(alice, 'bob@example.com', { cc: 'carol@example.com', encrypt: true }));
|
||||||
const parsed = await simpleParser(raw);
|
const parsed = await simpleParser(raw);
|
||||||
for (const reader of [bob, carol]) {
|
for (const reader of [bob, carol]) {
|
||||||
const result = await reader.mail.decrypt(parsed, { passphrase: reader.passphrase });
|
const result = await reader.mail.decrypt(parsed, { passphrase: reader.passphrase });
|
||||||
assert.match(result.parsed.text, /Top secret/);
|
assert.match(result.parsed.text, /Top secret/);
|
||||||
assert.equal(result.signatures.length, 0);
|
assert.equal(result.signatures.length, 0);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
test('encrypts and signs outgoing attachments with the message body', async () => {
|
test('encrypts and signs outgoing attachments with the message body', 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 exchange(alice, bob);
|
await exchange(alice, bob);
|
||||||
const contents = Buffer.from([0, 1, 2, 127, 128, 255]);
|
const contents = Buffer.from([0, 1, 2, 127, 128, 255]);
|
||||||
const { raw } = await alice.mail.build(sendOptions(alice, 'bob@example.com', {
|
const { raw } = await alice.mail.build(sendOptions(alice, 'bob@example.com', {
|
||||||
encrypt: true,
|
encrypt: true,
|
||||||
sign: true,
|
sign: true,
|
||||||
passphrase: alice.passphrase,
|
passphrase: alice.passphrase,
|
||||||
attachments: [{ filename: 'binary-data.bin', contentType: 'application/octet-stream', content: contents }]
|
attachments: [{ filename: 'binary-data.bin', contentType: 'application/octet-stream', content: contents }]
|
||||||
}));
|
}));
|
||||||
assert.ok(!raw.toString('latin1').includes(contents.toString('latin1')));
|
assert.ok(!raw.toString('latin1').includes(contents.toString('latin1')));
|
||||||
|
|
||||||
const parsed = await simpleParser(raw);
|
const parsed = await simpleParser(raw);
|
||||||
const decrypted = await bob.mail.decrypt(parsed, { passphrase: bob.passphrase });
|
const decrypted = await bob.mail.decrypt(parsed, { passphrase: bob.passphrase });
|
||||||
assert.equal(decrypted.parsed.text.trim(), 'Top secret ✓\nline two');
|
assert.equal(decrypted.parsed.text.trim(), 'Top secret ✓\nline two');
|
||||||
assert.equal(decrypted.parsed.attachments.length, 1);
|
assert.equal(decrypted.parsed.attachments.length, 1);
|
||||||
assert.equal(decrypted.parsed.attachments[0].filename, 'binary-data.bin');
|
assert.equal(decrypted.parsed.attachments[0].filename, 'binary-data.bin');
|
||||||
assert.equal(decrypted.parsed.attachments[0].contentType, 'application/octet-stream');
|
assert.equal(decrypted.parsed.attachments[0].contentType, 'application/octet-stream');
|
||||||
assert.deepEqual(decrypted.parsed.attachments[0].content, contents);
|
assert.deepEqual(decrypted.parsed.attachments[0].content, contents);
|
||||||
assert.equal(decrypted.signatures[0].status, 'valid');
|
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');
|
||||||
await exchange(alice, bob);
|
await exchange(alice, bob);
|
||||||
const { raw } = await alice.mail.build(sendOptions(alice, 'bob@example.com', { encrypt: true, sign: true, passphrase: alice.passphrase }));
|
const { raw } = await alice.mail.build(sendOptions(alice, 'bob@example.com', { encrypt: true, sign: true, passphrase: alice.passphrase }));
|
||||||
const text = raw.toString('latin1');
|
const text = raw.toString('latin1');
|
||||||
const lines = text.split('\r\n');
|
const lines = text.split('\r\n');
|
||||||
const at = lines.findIndex((line, index) => index > 5 && line.length >= 60 && !line.startsWith('-') && !line.includes(':'));
|
const at = lines.findIndex((line, index) => index > 5 && line.length >= 60 && !line.startsWith('-') && !line.includes(':'));
|
||||||
lines[at] = lines[at].slice(0, 20) + (lines[at][20] === 'A' ? 'B' : 'A') + lines[at].slice(21);
|
lines[at] = lines[at].slice(0, 20) + (lines[at][20] === 'A' ? 'B' : 'A') + lines[at].slice(21);
|
||||||
const broken = await simpleParser(Buffer.from(lines.join('\r\n'), 'latin1'));
|
const broken = await simpleParser(Buffer.from(lines.join('\r\n'), 'latin1'));
|
||||||
await assert.rejects(() => bob.mail.decrypt(broken, { passphrase: bob.passphrase }), error => ['CORRUPT'].includes(error.code));
|
await assert.rejects(() => bob.mail.decrypt(broken, { passphrase: bob.passphrase }), error => ['CORRUPT'].includes(error.code));
|
||||||
const empty = await simpleParser(Buffer.from(text.replace(/-----BEGIN PGP MESSAGE-----[\s\S]*-----END PGP MESSAGE-----/, 'nothing'), 'latin1'));
|
const empty = await simpleParser(Buffer.from(text.replace(/-----BEGIN PGP MESSAGE-----[\s\S]*-----END PGP MESSAGE-----/, 'nothing'), 'latin1'));
|
||||||
await assert.rejects(() => bob.mail.decrypt(empty), error => error.code === 'CORRUPT');
|
await assert.rejects(() => bob.mail.decrypt(empty), error => error.code === 'CORRUPT');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('reports unknown signers and a changed key for a known sender', async () => {
|
test('reports unknown signers and a changed key for a known sender', 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) });
|
||||||
await alice.keyStore.addContact({ armoredKey: await bob.keyStore.exportPublic(bob.key.fingerprint) });
|
await alice.keyStore.addContact({ armoredKey: await bob.keyStore.exportPublic(bob.key.fingerprint) });
|
||||||
const impostor = await actor('Alice', 'alice@example.com');
|
const impostor = await actor('Alice', 'alice@example.com');
|
||||||
await impostor.keyStore.addContact({ armoredKey: await bob.keyStore.exportPublic(bob.key.fingerprint) });
|
await impostor.keyStore.addContact({ armoredKey: await bob.keyStore.exportPublic(bob.key.fingerprint) });
|
||||||
const { raw } = await impostor.mail.build(sendOptions(impostor, 'bob@example.com', { encrypt: true, sign: true, passphrase: impostor.passphrase }));
|
const { raw } = await impostor.mail.build(sendOptions(impostor, 'bob@example.com', { encrypt: true, sign: true, passphrase: impostor.passphrase }));
|
||||||
const result = await bob.mail.decrypt(await simpleParser(raw), { passphrase: bob.passphrase });
|
const result = await bob.mail.decrypt(await simpleParser(raw), { passphrase: bob.passphrase });
|
||||||
assert.equal(result.signatures[0].status, 'unknown-key');
|
assert.equal(result.signatures[0].status, 'unknown-key');
|
||||||
assert.equal(result.signatures[0].keyChanged, true);
|
assert.equal(result.signatures[0].keyChanged, true);
|
||||||
const added = await bob.keyStore.addContact({ armoredKey: await impostor.keyStore.exportPublic(impostor.key.fingerprint) });
|
const added = await bob.keyStore.addContact({ armoredKey: await impostor.keyStore.exportPublic(impostor.key.fingerprint) });
|
||||||
assert.deepEqual(added.keyChangedFrom, [alice.key.fingerprint]);
|
assert.deepEqual(added.keyChangedFrom, [alice.key.fingerprint]);
|
||||||
const second = await bob.mail.decrypt(await simpleParser(raw));
|
const second = await bob.mail.decrypt(await simpleParser(raw));
|
||||||
assert.equal(second.signatures[0].status, 'valid');
|
assert.equal(second.signatures[0].status, 'valid');
|
||||||
assert.equal(second.signatures[0].keyChanged, false);
|
assert.equal(second.signatures[0].keyChanged, false);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('signs without encrypting and verifies PGP/MIME signatures', async () => {
|
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 attachment = Buffer.from('signed attachment data');
|
const attachment = Buffer.from('signed attachment data');
|
||||||
const { raw } = await alice.mail.build(sendOptions(alice, 'bob@example.com', {
|
const { raw } = await alice.mail.build(sendOptions(alice, 'bob@example.com', {
|
||||||
sign: true,
|
sign: true,
|
||||||
passphrase: alice.passphrase,
|
passphrase: alice.passphrase,
|
||||||
attachments: [{ filename: 'signed.txt', contentType: 'text/plain', content: attachment }]
|
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);
|
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');
|
||||||
const [bad] = await bob.mail.verifySigned(await simpleParser(altered), altered);
|
const [bad] = await bob.mail.verifySigned(await simpleParser(altered), altered);
|
||||||
assert.equal(bad.status, 'invalid');
|
assert.equal(bad.status, 'invalid');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('reads inline PGP messages and cleartext signatures', async () => {
|
test('reads inline PGP messages and cleartext 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 exchange(alice, bob);
|
await exchange(alice, bob);
|
||||||
const bobKey = (await openpgp.readKey({ armoredKey: await bob.keyStore.exportPublic(bob.key.fingerprint) }));
|
const bobKey = (await openpgp.readKey({ armoredKey: await bob.keyStore.exportPublic(bob.key.fingerprint) }));
|
||||||
const armored = await openpgp.encrypt({ message: await openpgp.createMessage({ text: 'inline body' }), encryptionKeys: bobKey });
|
const armored = await openpgp.encrypt({ message: await openpgp.createMessage({ text: 'inline body' }), encryptionKeys: bobKey });
|
||||||
const source = Buffer.from(`From: Alice <alice@example.com>\r\nTo: bob@example.com\r\nSubject: inline\r\nContent-Type: text/plain\r\n\r\n${armored}\r\n`);
|
const source = Buffer.from(`From: Alice <alice@example.com>\r\nTo: bob@example.com\r\nSubject: inline\r\nContent-Type: text/plain\r\n\r\n${armored}\r\n`);
|
||||||
const parsed = await simpleParser(source);
|
const parsed = await simpleParser(source);
|
||||||
assert.equal(detect(parsed), 'encrypted-inline');
|
assert.equal(detect(parsed), 'encrypted-inline');
|
||||||
const result = await bob.mail.decrypt(parsed, { passphrase: bob.passphrase });
|
const result = await bob.mail.decrypt(parsed, { passphrase: bob.passphrase });
|
||||||
assert.equal(result.parsed.text.trim(), 'inline body');
|
assert.equal(result.parsed.text.trim(), 'inline body');
|
||||||
const aliceSigner = await alice.keyStore.unlockKey(alice.key.fingerprint, alice.passphrase);
|
const aliceSigner = await alice.keyStore.unlockKey(alice.key.fingerprint, alice.passphrase);
|
||||||
const cleartext = await openpgp.sign({ message: await openpgp.createCleartextMessage({ text: 'hello signed' }), signingKeys: aliceSigner });
|
const cleartext = await openpgp.sign({ message: await openpgp.createCleartextMessage({ text: 'hello signed' }), signingKeys: aliceSigner });
|
||||||
const signedSource = Buffer.from(`From: alice@example.com\r\nSubject: s\r\nContent-Type: text/plain\r\n\r\n${cleartext}\r\n`);
|
const signedSource = Buffer.from(`From: alice@example.com\r\nSubject: s\r\nContent-Type: text/plain\r\n\r\n${cleartext}\r\n`);
|
||||||
const signedParsed = await simpleParser(signedSource);
|
const signedParsed = await simpleParser(signedSource);
|
||||||
assert.equal(detect(signedParsed), 'signed-inline');
|
assert.equal(detect(signedParsed), 'signed-inline');
|
||||||
assert.equal((await bob.mail.verifySigned(signedParsed, signedSource))[0].status, 'valid');
|
assert.equal((await bob.mail.verifySigned(signedParsed, signedSource))[0].status, 'valid');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('decrypts large messages with attachments from other clients', async () => {
|
test('decrypts large messages with attachments from other clients', 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');
|
||||||
const inner = await new Promise((resolve, reject) => new MailComposer({
|
const inner = await new Promise((resolve, reject) => new MailComposer({
|
||||||
text: 'with attachment', attachments: [{ filename: 'big.bin', content: Buffer.alloc(8 * 1048576, 7) }]
|
text: 'with attachment', attachments: [{ filename: 'big.bin', content: Buffer.alloc(8 * 1048576, 7) }]
|
||||||
}).compile().build((error, message) => error ? reject(error) : resolve(message)));
|
}).compile().build((error, message) => error ? reject(error) : resolve(message)));
|
||||||
const bobKey = await openpgp.readKey({ armoredKey: await bob.keyStore.exportPublic(bob.key.fingerprint) });
|
const bobKey = await openpgp.readKey({ armoredKey: await bob.keyStore.exportPublic(bob.key.fingerprint) });
|
||||||
const armored = await openpgp.encrypt({ message: await openpgp.createMessage({ binary: inner }), encryptionKeys: bobKey });
|
const armored = await openpgp.encrypt({ message: await openpgp.createMessage({ binary: inner }), encryptionKeys: bobKey });
|
||||||
const source = Buffer.from(`From: alice@example.com\r\nTo: bob@example.com\r\nSubject: big\r\nMIME-Version: 1.0\r\nContent-Type: multipart/encrypted; protocol="application/pgp-encrypted"; boundary="b1"\r\n\r\n--b1\r\nContent-Type: application/pgp-encrypted\r\n\r\nVersion: 1\r\n\r\n--b1\r\nContent-Type: application/octet-stream\r\n\r\n${armored}\r\n--b1--\r\n`);
|
const source = Buffer.from(`From: alice@example.com\r\nTo: bob@example.com\r\nSubject: big\r\nMIME-Version: 1.0\r\nContent-Type: multipart/encrypted; protocol="application/pgp-encrypted"; boundary="b1"\r\n\r\n--b1\r\nContent-Type: application/pgp-encrypted\r\n\r\nVersion: 1\r\n\r\n--b1\r\nContent-Type: application/octet-stream\r\n\r\n${armored}\r\n--b1--\r\n`);
|
||||||
const result = await bob.mail.decrypt(await simpleParser(source), { passphrase: bob.passphrase });
|
const result = await bob.mail.decrypt(await simpleParser(source), { passphrase: bob.passphrase });
|
||||||
assert.equal(result.parsed.attachments[0].filename, 'big.bin');
|
assert.equal(result.parsed.attachments[0].filename, 'big.bin');
|
||||||
assert.equal(result.parsed.attachments[0].content.length, 8 * 1048576);
|
assert.equal(result.parsed.attachments[0].content.length, 8 * 1048576);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('keyring: contacts, trust levels, expired passphrase cache and settings', async () => {
|
test('keyring: contacts, trust levels, expired passphrase cache and settings', 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');
|
||||||
const { contact } = await alice.keyStore.addContact({ armoredKey: await bob.keyStore.exportPublic(bob.key.fingerprint), source: 'message' });
|
const { contact } = await alice.keyStore.addContact({ armoredKey: await bob.keyStore.exportPublic(bob.key.fingerprint), source: 'message' });
|
||||||
assert.equal(contact.trust, 'unknown');
|
assert.equal(contact.trust, 'unknown');
|
||||||
assert.equal((await alice.keyStore.setTrust(contact.fingerprint, 'verified')).trust, 'verified');
|
assert.equal((await alice.keyStore.setTrust(contact.fingerprint, 'verified')).trust, 'verified');
|
||||||
await assert.rejects(() => alice.keyStore.setTrust(contact.fingerprint, 'bogus'));
|
await assert.rejects(() => alice.keyStore.setTrust(contact.fingerprint, 'bogus'));
|
||||||
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, customKeyServers: [], enabledKeyServers: [] });
|
assert.deepEqual(await alice.keyStore.getSettings(), { cacheMinutes: 10, customKeyServers: [], enabledKeyServers: [] });
|
||||||
const customServer = { id: 'custom', name: 'Example', url: 'https://keys.example.org/', protocol: 'hkp' };
|
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'] });
|
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 });
|
await alice.keyStore.setSettings({ cacheMinutes: 5 });
|
||||||
assert.deepEqual((await alice.keyStore.getSettings()).customKeyServers, [customServer]);
|
assert.deepEqual((await alice.keyStore.getSettings()).customKeyServers, [customServer]);
|
||||||
assert.deepEqual((await alice.keyStore.getSettings()).enabledKeyServers, ['custom', 'openpgp-vks']);
|
assert.deepEqual((await alice.keyStore.getSettings()).enabledKeyServers, ['custom', 'openpgp-vks']);
|
||||||
await alice.keyStore.setSettings({ cacheMinutes: 5, enabledKeyServers: [] });
|
await alice.keyStore.setSettings({ cacheMinutes: 5, enabledKeyServers: [] });
|
||||||
assert.deepEqual((await alice.keyStore.getSettings()).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);
|
||||||
|
|
||||||
let clock = 1000;
|
let clock = 1000;
|
||||||
const cache = createPassphraseCache(async () => 1, () => clock);
|
const cache = createPassphraseCache(async () => 1, () => clock);
|
||||||
await cache.remember('F', 'secret');
|
await cache.remember('F', 'secret');
|
||||||
assert.equal(cache.get('F'), 'secret');
|
assert.equal(cache.get('F'), 'secret');
|
||||||
clock += 61000;
|
clock += 61000;
|
||||||
assert.equal(cache.get('F'), null);
|
assert.equal(cache.get('F'), null);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -3,29 +3,29 @@ const accountMailUi = window.epMailFeatures.mail;
|
|||||||
const accountDavUi = window.epMailFeatures.dav;
|
const accountDavUi = window.epMailFeatures.dav;
|
||||||
|
|
||||||
async function openAccountManager(){
|
async function openAccountManager(){
|
||||||
const root=accountMailUi.select('#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>${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('');
|
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();accountMailUi.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{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}
|
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();accountDavUi.openManager(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)accountMailUi.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;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}
|
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){accountMailUi.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);
|
||||||
})();
|
})();
|
||||||
|
|||||||
@@ -2,40 +2,40 @@
|
|||||||
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 state = window.epMailState;
|
const state = window.epMailState;
|
||||||
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]))}
|
||||||
const { safeRemoteImageUrl, sanitizeMailHtml } = window.epMailFeatures.contentSecurity;
|
const { safeRemoteImageUrl, sanitizeMailHtml } = window.epMailFeatures.contentSecurity;
|
||||||
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 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){
|
function openMessage(id){
|
||||||
state.activeMessage=id;
|
state.activeMessage=id;
|
||||||
const m=state.messages.find(x=>x.id===id);
|
const m=state.messages.find(x=>x.id===id);
|
||||||
if(!m)return;
|
if(!m)return;
|
||||||
m.unread=false;
|
m.unread=false;
|
||||||
renderList();
|
renderList();
|
||||||
let safeHtml={html:'',remoteImageCount:0};
|
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)}
|
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 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 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('');
|
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>`;
|
$('#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',()=>{
|
$('#load-remote-images')?.addEventListener('click',()=>{
|
||||||
$('#reader-pane').querySelectorAll('.reader-body img[data-remote-src]').forEach(image=>{
|
$('#reader-pane').querySelectorAll('.reader-body img[data-remote-src]').forEach(image=>{
|
||||||
const url=safeRemoteImageUrl(image.getAttribute('data-remote-src'));
|
const url=safeRemoteImageUrl(image.getAttribute('data-remote-src'));
|
||||||
image.removeAttribute('data-remote-src');
|
image.removeAttribute('data-remote-src');
|
||||||
if(url)image.src=url;
|
if(url)image.src=url;
|
||||||
});
|
});
|
||||||
$('.remote-image-notice')?.remove();
|
$('.remote-image-notice')?.remove();
|
||||||
});
|
});
|
||||||
$('#reader-archive').onclick=()=>{m.archived=true;toast('Moved to Archive');renderList();$('#reader-pane').innerHTML=emptyReader()};
|
$('#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-delete').onclick=()=>{m.deleted=true;toast('Moved to Trash');renderList();$('#reader-pane').innerHTML=emptyReader()};
|
||||||
$('#reader-star').onclick=()=>{m.star=!m.star;renderList();openMessage(id)};
|
$('#reader-star').onclick=()=>{m.star=!m.star;renderList();openMessage(id)};
|
||||||
$('#reply').onclick=()=>showCompose(m);
|
$('#reply').onclick=()=>showCompose(m);
|
||||||
$('#forward').onclick=()=>showCompose(m,true);
|
$('#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(state.toastTimer);state.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;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 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){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 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();}
|
||||||
$$('.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);
|
$$('.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);
|
||||||
|
|
||||||
window.epMailShell = Object.freeze({
|
window.epMailShell = Object.freeze({
|
||||||
state,
|
state,
|
||||||
|
|||||||
@@ -5,159 +5,159 @@ const selectAttachmentUi = attachmentMailUi.select;
|
|||||||
const selectAllAttachmentUi = attachmentMailUi.selectAll;
|
const selectAllAttachmentUi = attachmentMailUi.selectAll;
|
||||||
const toastAttachmentUi = attachmentMailUi.toast;
|
const toastAttachmentUi = attachmentMailUi.toast;
|
||||||
const attachmentFolders = ['Inbox', 'Sent', 'Archive', 'Trash'];
|
const attachmentFolders = ['Inbox', 'Sent', 'Archive', 'Trash'];
|
||||||
let attachmentItems = [];
|
let attachmentItems = [];
|
||||||
|
|
||||||
function attachmentKind(filename) {
|
function attachmentKind(filename) {
|
||||||
const ext = String(filename).toLowerCase().split('.').pop();
|
const ext = String(filename).toLowerCase().split('.').pop();
|
||||||
if (['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'svg'].includes(ext)) return 'Images';
|
if (['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'svg'].includes(ext)) return 'Images';
|
||||||
if (['pdf', 'doc', 'docx', 'odt', 'txt', 'rtf', 'md', 'xls', 'xlsx', 'csv', 'ppt', 'pptx'].includes(ext)) return 'Documents';
|
if (['pdf', 'doc', 'docx', 'odt', 'txt', 'rtf', 'md', 'xls', 'xlsx', 'csv', 'ppt', 'pptx'].includes(ext)) return 'Documents';
|
||||||
if (['zip', 'rar', '7z', 'tar', 'gz'].includes(ext)) return 'Archives';
|
if (['zip', 'rar', '7z', 'tar', 'gz'].includes(ext)) return 'Archives';
|
||||||
return 'Other';
|
return 'Other';
|
||||||
}
|
}
|
||||||
|
|
||||||
function attachmentSize(size) {
|
function attachmentSize(size) {
|
||||||
if (!size) return '';
|
if (!size) return '';
|
||||||
if (typeof size === 'string') return size;
|
if (typeof size === 'string') return size;
|
||||||
return size < 1048576 ? `${Math.max(1, Math.round(size / 1024))} KB` : `${(size / 1048576).toFixed(1)} MB`;
|
return size < 1048576 ? `${Math.max(1, Math.round(size / 1024))} KB` : `${(size / 1048576).toFixed(1)} MB`;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function previewAttachment(target, details) {
|
async function previewAttachment(target, details) {
|
||||||
if (!details.uid || !window.daybreakMail?.previewAttachment) {
|
if (!details.uid || !window.daybreakMail?.previewAttachment) {
|
||||||
target.textContent = 'Previews are available for connected mailbox messages.';
|
target.textContent = 'Previews are available for connected mailbox messages.';
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
target.textContent = 'Loading preview…';
|
target.textContent = 'Loading preview…';
|
||||||
try {
|
try {
|
||||||
const result = await window.daybreakMail.previewAttachment(details);
|
const result = await window.daybreakMail.previewAttachment(details);
|
||||||
target.replaceChildren();
|
target.replaceChildren();
|
||||||
if (result.kind === 'image') {
|
if (result.kind === 'image') {
|
||||||
const image = document.createElement('img');
|
const image = document.createElement('img');
|
||||||
image.className = 'attachment-preview-image';
|
image.className = 'attachment-preview-image';
|
||||||
image.alt = details.filename;
|
image.alt = details.filename;
|
||||||
image.src = result.dataUrl;
|
image.src = result.dataUrl;
|
||||||
target.append(image);
|
target.append(image);
|
||||||
} else if (result.kind === 'text') {
|
} else if (result.kind === 'text') {
|
||||||
const pre = document.createElement('pre');
|
const pre = document.createElement('pre');
|
||||||
pre.className = 'attachment-preview-text';
|
pre.className = 'attachment-preview-text';
|
||||||
pre.textContent = result.text + (result.truncated ? '\n… (preview truncated)' : '');
|
pre.textContent = result.text + (result.truncated ? '\n… (preview truncated)' : '');
|
||||||
target.append(pre);
|
target.append(pre);
|
||||||
} else {
|
} else {
|
||||||
target.textContent = result.reason || 'No preview is available for this file type.';
|
target.textContent = result.reason || 'No preview is available for this file type.';
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
target.textContent = error.message || 'Could not load the preview.';
|
target.textContent = error.message || 'Could not load the preview.';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function downloadAttachment(details) {
|
function downloadAttachment(details) {
|
||||||
if (!details.uid || !window.daybreakMail?.saveAttachment) { toastAttachmentUi('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) toastAttachmentUi('Attachment saved'); })
|
.then(result => { if (result.saved) toastAttachmentUi('Attachment saved'); })
|
||||||
.catch(error => toastAttachmentUi(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.
|
||||||
attachmentMailUi.wrapOpenMessage(baseOpenMessage => function (id) {
|
attachmentMailUi.wrapOpenMessage(baseOpenMessage => function (id) {
|
||||||
baseOpenMessage(id);
|
baseOpenMessage(id);
|
||||||
const message = attachmentMailUi.state.messages.find(item => item.id === id);
|
const message = attachmentMailUi.state.messages.find(item => item.id === id);
|
||||||
if (!message?.uid) return;
|
if (!message?.uid) return;
|
||||||
selectAllAttachmentUi('#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');
|
||||||
button.className = 'preview-attachment icon-button';
|
button.className = 'preview-attachment icon-button';
|
||||||
button.title = 'Preview';
|
button.title = 'Preview';
|
||||||
button.setAttribute('aria-label', `Preview ${download.dataset.filename}`);
|
button.setAttribute('aria-label', `Preview ${download.dataset.filename}`);
|
||||||
button.textContent = '👁';
|
button.textContent = '👁';
|
||||||
button.addEventListener('click', event => {
|
button.addEventListener('click', event => {
|
||||||
event.stopPropagation();
|
event.stopPropagation();
|
||||||
let panel = row.nextElementSibling?.classList.contains('attachment-preview') ? row.nextElementSibling : null;
|
let panel = row.nextElementSibling?.classList.contains('attachment-preview') ? row.nextElementSibling : null;
|
||||||
if (panel) { panel.remove(); return; }
|
if (panel) { panel.remove(); return; }
|
||||||
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 || attachmentMailUi.state.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 = [];
|
||||||
for (const folder of attachmentFolders) {
|
for (const folder of attachmentFolders) {
|
||||||
let offset = 0;
|
let offset = 0;
|
||||||
for (let page = 0; page < 5; page += 1) {
|
for (let page = 0; page < 5; page += 1) {
|
||||||
const result = await window.daybreakMail.syncFolder(folder, offset, { hasAttachments: true });
|
const result = await window.daybreakMail.syncFolder(folder, offset, { hasAttachments: true });
|
||||||
for (const message of result.messages || []) {
|
for (const message of result.messages || []) {
|
||||||
for (const file of message.attachments || []) {
|
for (const file of message.attachments || []) {
|
||||||
items.push({
|
items.push({
|
||||||
uid: message.uid, folder, filename: file.filename, size: file.size,
|
uid: message.uid, folder, filename: file.filename, size: file.size,
|
||||||
subject: message.subject, sender: message.sender, date: message.date, timestamp: Number(message.timestamp || 0),
|
subject: message.subject, sender: message.sender, date: message.date, timestamp: Number(message.timestamp || 0),
|
||||||
kind: attachmentKind(file.filename)
|
kind: attachmentKind(file.filename)
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
offset += (result.messages || []).length;
|
offset += (result.messages || []).length;
|
||||||
if (!result.messages?.length || offset >= (result.total || 0)) break;
|
if (!result.messages?.length || offset >= (result.total || 0)) break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return items.sort((a, b) => b.timestamp - a.timestamp);
|
return items.sort((a, b) => b.timestamp - a.timestamp);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function openAttachmentsView() {
|
async function openAttachmentsView() {
|
||||||
if (!attachmentMailUi.connectedAccount || !window.daybreakMail) { attachmentMailUi.openMailAccount(); return; }
|
if (!attachmentMailUi.connectedAccount || !window.daybreakMail) { attachmentMailUi.openMailAccount(); return; }
|
||||||
const root = selectAttachmentUi('#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 = selectAttachmentUi('#attachment-list');
|
const list = selectAttachmentUi('#attachment-list');
|
||||||
const render = () => {
|
const render = () => {
|
||||||
const text = selectAttachmentUi('#attachment-search').value.trim().toLowerCase();
|
const text = selectAttachmentUi('#attachment-search').value.trim().toLowerCase();
|
||||||
const type = selectAttachmentUi('#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();
|
||||||
if (!shown.length) { list.textContent = attachmentItems.length ? 'No attachments match.' : 'No attachments found.'; return; }
|
if (!shown.length) { list.textContent = attachmentItems.length ? 'No attachments match.' : 'No attachments found.'; return; }
|
||||||
shown.forEach(item => {
|
shown.forEach(item => {
|
||||||
const row = document.createElement('div');
|
const row = document.createElement('div');
|
||||||
row.className = 'attachment-row';
|
row.className = 'attachment-row';
|
||||||
const info = document.createElement('div');
|
const info = document.createElement('div');
|
||||||
info.className = 'attachment-row-info';
|
info.className = 'attachment-row-info';
|
||||||
const name = document.createElement('strong');
|
const name = document.createElement('strong');
|
||||||
name.textContent = item.filename;
|
name.textContent = item.filename;
|
||||||
const meta = document.createElement('small');
|
const meta = document.createElement('small');
|
||||||
meta.textContent = [attachmentSize(item.size), item.sender, item.subject, item.folder, item.date].filter(Boolean).join(' · ');
|
meta.textContent = [attachmentSize(item.size), item.sender, item.subject, item.folder, item.date].filter(Boolean).join(' · ');
|
||||||
info.append(name, meta);
|
info.append(name, meta);
|
||||||
const preview = document.createElement('button');
|
const preview = document.createElement('button');
|
||||||
preview.className = 'discard';
|
preview.className = 'discard';
|
||||||
preview.textContent = 'Preview';
|
preview.textContent = 'Preview';
|
||||||
const save = document.createElement('button');
|
const save = document.createElement('button');
|
||||||
save.className = 'discard';
|
save.className = 'discard';
|
||||||
save.textContent = 'Download';
|
save.textContent = 'Download';
|
||||||
const panel = document.createElement('div');
|
const panel = document.createElement('div');
|
||||||
panel.className = 'attachment-preview';
|
panel.className = 'attachment-preview';
|
||||||
panel.hidden = true;
|
panel.hidden = true;
|
||||||
const details = { uid: item.uid, folder: item.folder, filename: item.filename };
|
const details = { uid: item.uid, folder: item.folder, filename: item.filename };
|
||||||
preview.onclick = () => {
|
preview.onclick = () => {
|
||||||
panel.hidden = !panel.hidden;
|
panel.hidden = !panel.hidden;
|
||||||
if (!panel.hidden && !panel.childElementCount && !panel.textContent) void previewAttachment(panel, details);
|
if (!panel.hidden && !panel.childElementCount && !panel.textContent) void previewAttachment(panel, details);
|
||||||
};
|
};
|
||||||
save.onclick = () => downloadAttachment(details);
|
save.onclick = () => downloadAttachment(details);
|
||||||
row.append(info, preview, save, panel);
|
row.append(info, preview, save, panel);
|
||||||
list.append(row);
|
list.append(row);
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
selectAttachmentUi('#attachment-search').oninput = render;
|
selectAttachmentUi('#attachment-search').oninput = render;
|
||||||
selectAttachmentUi('#attachment-type').onchange = render;
|
selectAttachmentUi('#attachment-type').onchange = render;
|
||||||
try {
|
try {
|
||||||
attachmentItems = await collectAttachments();
|
attachmentItems = await collectAttachments();
|
||||||
if (selectAttachmentUi('#attachment-list')) render();
|
if (selectAttachmentUi('#attachment-list')) render();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (selectAttachmentUi('#attachment-list')) selectAttachmentUi('#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', () => {
|
||||||
selectAttachmentUi('#attachments-nav')?.addEventListener('click', openAttachmentsView);
|
selectAttachmentUi('#attachments-nav')?.addEventListener('click', openAttachmentsView);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,30 +1,30 @@
|
|||||||
.brand-mark,
|
.brand-mark,
|
||||||
body.wasteland .brand-mark,
|
body.wasteland .brand-mark,
|
||||||
body.ep-wasteland .brand-mark,
|
body.ep-wasteland .brand-mark,
|
||||||
body.ep-daylight .brand-mark {
|
body.ep-daylight .brand-mark {
|
||||||
background: transparent !important;
|
background: transparent !important;
|
||||||
box-shadow: none !important;
|
box-shadow: none !important;
|
||||||
border-radius: 0;
|
border-radius: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.brand-mark img {
|
.brand-mark img {
|
||||||
display: block;
|
display: block;
|
||||||
width: 35px;
|
width: 35px;
|
||||||
height: 35px;
|
height: 35px;
|
||||||
object-fit: contain;
|
object-fit: contain;
|
||||||
}
|
}
|
||||||
|
|
||||||
.settings-select {
|
.settings-select {
|
||||||
flex: 1;
|
flex: 1;
|
||||||
border: 0;
|
border: 0;
|
||||||
padding: 5px 0;
|
padding: 5px 0;
|
||||||
background: transparent;
|
background: transparent;
|
||||||
color: var(--text);
|
color: var(--text);
|
||||||
font: inherit;
|
font: inherit;
|
||||||
text-align: right;
|
text-align: right;
|
||||||
}
|
}
|
||||||
|
|
||||||
body.ep-wasteland .settings-select,
|
body.ep-wasteland .settings-select,
|
||||||
body.ep-daylight .settings-select {
|
body.ep-daylight .settings-select {
|
||||||
color-scheme: inherit;
|
color-scheme: inherit;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,42 +3,42 @@ const davProductivityUi = window.epMailFeatures.productivity;
|
|||||||
const selectDavUi = davProductivityUi.select;
|
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'?davProductivityUi.events.filter(item=>!item._dav):davProductivityUi.contacts.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){davProductivityUi.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}`)}}
|
||||||
davProductivityUi.events=[...localOnly,...result.items];
|
davProductivityUi.events=[...localOnly,...result.items];
|
||||||
davProductivityUi.productWrite(davProductivityUi.productKeys.events,davProductivityUi.events);davProductivityUi.renderCalendar();davProductivityUi.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){davProductivityUi.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}`)}}
|
||||||
davProductivityUi.contacts=[...localOnly,...result.items];
|
davProductivityUi.contacts=[...localOnly,...result.items];
|
||||||
davProductivityUi.productWrite(davProductivityUi.productKeys.contacts,davProductivityUi.contacts);davProductivityUi.renderContacts();davProductivityUi.toast(`Synced ${result.items.length} contacts`);
|
davProductivityUi.productWrite(davProductivityUi.productKeys.contacts,davProductivityUi.contacts);davProductivityUi.renderContacts();davProductivityUi.toast(`Synced ${result.items.length} contacts`);
|
||||||
}
|
}
|
||||||
}catch(error){davProductivityUi.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=selectDavUi('#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>${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('');
|
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){davProductivityUi.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'){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)} }
|
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){davProductivityUi.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=selectDavUi('#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();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-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({
|
window.epMailFeatures.dav = Object.freeze({
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
|
||||||
<rect width="64" height="64" rx="12" fill="#0a0c0b"/>
|
<rect width="64" height="64" rx="12" fill="#0a0c0b"/>
|
||||||
<g fill="none" stroke="#eee9de">
|
<g fill="none" stroke="#eee9de">
|
||||||
<circle cx="32" cy="32" r="27" stroke-width="3"/>
|
<circle cx="32" cy="32" r="27" stroke-width="3"/>
|
||||||
<path d="M32 4v56" stroke-width="4"/>
|
<path d="M32 4v56" stroke-width="4"/>
|
||||||
<ellipse cx="32" cy="18" rx="12" ry="5" stroke-width="3" transform="rotate(22 32 18)"/>
|
<ellipse cx="32" cy="18" rx="12" ry="5" stroke-width="3" transform="rotate(22 32 18)"/>
|
||||||
<ellipse cx="32" cy="46" rx="12" ry="5" stroke-width="3" transform="rotate(-22 32 46)"/>
|
<ellipse cx="32" cy="46" rx="12" ry="5" stroke-width="3" transform="rotate(-22 32 46)"/>
|
||||||
<ellipse cx="32" cy="32" rx="8" ry="8" stroke-width="2" opacity=".75" transform="rotate(45 32 32)"/>
|
<ellipse cx="32" cy="32" rx="8" ry="8" stroke-width="2" opacity=".75" transform="rotate(45 32 32)"/>
|
||||||
</g>
|
</g>
|
||||||
</svg>
|
</svg>
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 552 B After Width: | Height: | Size: 562 B |
@@ -1,67 +1,67 @@
|
|||||||
<!doctype html>
|
<!doctype html>
|
||||||
<html lang="en">
|
<html lang="en">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<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: https:; font-src 'self'; connect-src 'none'; frame-src 'none'; object-src 'none'; base-uri 'none'; form-action '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">
|
||||||
<link rel="stylesheet" href="branding.css">
|
<link rel="stylesheet" href="branding.css">
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div class="app-shell">
|
<div class="app-shell">
|
||||||
<aside class="rail" aria-label="Main navigation">
|
<aside class="rail" aria-label="Main navigation">
|
||||||
<div class="brand-mark" title="ep-mail"><img id="brand-logo" src="logo-ep-daylight.svg" alt="Eternity Project"></div>
|
<div class="brand-mark" title="ep-mail"><img id="brand-logo" src="logo-ep-daylight.svg" alt="Eternity Project"></div>
|
||||||
<button class="rail-button active" data-view="mail" aria-label="Mail"><span>✉</span></button>
|
<button class="rail-button active" data-view="mail" aria-label="Mail"><span>✉</span></button>
|
||||||
<button class="rail-button" data-view="calendar" aria-label="Calendar"><span>▦</span></button>
|
<button class="rail-button" data-view="calendar" aria-label="Calendar"><span>▦</span></button>
|
||||||
<button class="rail-button" data-view="contacts" aria-label="Contacts"><span>♙</span></button>
|
<button class="rail-button" data-view="contacts" aria-label="Contacts"><span>♙</span></button>
|
||||||
<div class="rail-spacer"></div>
|
<div class="rail-spacer"></div>
|
||||||
</aside>
|
</aside>
|
||||||
|
|
||||||
<aside class="sidebar">
|
<aside class="sidebar">
|
||||||
<div class="sidebar-head"><div><p class="eyebrow">YOUR WORKSPACE</p><h1 id="sidebar-title">Inbox</h1></div><button class="icon-button" id="sidebar-menu" aria-label="More options">···</button></div>
|
<div class="sidebar-head"><div><p class="eyebrow">YOUR WORKSPACE</p><h1 id="sidebar-title">Inbox</h1></div><button class="icon-button" id="sidebar-menu" aria-label="More options">···</button></div>
|
||||||
<div class="account-card" id="account-settings" role="button" tabindex="0" title="Set up a mail account"><div class="account-avatar">✉</div><div class="account-info"><strong>Mail accounts</strong><span>Manage connected mailboxes</span></div><span class="online-dot"></span></div>
|
<div class="account-card" id="account-settings" role="button" tabindex="0" title="Set up a mail account"><div class="account-avatar">✉</div><div class="account-info"><strong>Mail accounts</strong><span>Manage connected mailboxes</span></div><span class="online-dot"></span></div>
|
||||||
<div class="section-label folders-head"><span>FOLDERS</span><button class="folder-add" id="add-folder" aria-label="Create folder">+</button></div>
|
<div class="section-label folders-head"><span>FOLDERS</span><button class="folder-add" id="add-folder" aria-label="Create folder">+</button></div>
|
||||||
<nav id="mail-nav" class="folder-nav" aria-label="Mail folders">
|
<nav id="mail-nav" class="folder-nav" aria-label="Mail folders">
|
||||||
<button class="folder active" data-folder="Inbox"><span class="nav-glyph">▣</span><span>Inbox</span></button>
|
<button class="folder active" data-folder="Inbox"><span class="nav-glyph">▣</span><span>Inbox</span></button>
|
||||||
<button class="folder" data-folder="Starred"><span class="nav-glyph">☆</span><span>Starred</span></button>
|
<button class="folder" data-folder="Starred"><span class="nav-glyph">☆</span><span>Starred</span></button>
|
||||||
<button class="folder" data-folder="Snoozed"><span class="nav-glyph">◷</span><span>Snoozed</span></button>
|
<button class="folder" data-folder="Snoozed"><span class="nav-glyph">◷</span><span>Snoozed</span></button>
|
||||||
<button class="folder" data-folder="Sent"><span class="nav-glyph">↗</span><span>Sent</span></button>
|
<button class="folder" data-folder="Sent"><span class="nav-glyph">↗</span><span>Sent</span></button>
|
||||||
<button class="folder" data-folder="Drafts"><span class="nav-glyph">▤</span><span>Drafts</span></button>
|
<button class="folder" data-folder="Drafts"><span class="nav-glyph">▤</span><span>Drafts</span></button>
|
||||||
<button class="folder" data-folder="Archive"><span class="nav-glyph">▱</span><span>Archive</span></button>
|
<button class="folder" data-folder="Archive"><span class="nav-glyph">▱</span><span>Archive</span></button>
|
||||||
<button class="folder" data-folder="Trash"><span class="nav-glyph">⌫</span><span>Trash</span></button>
|
<button class="folder" data-folder="Trash"><span class="nav-glyph">⌫</span><span>Trash</span></button>
|
||||||
<div id="custom-folders"></div>
|
<div id="custom-folders"></div>
|
||||||
</nav>
|
</nav>
|
||||||
<button class="label-link" id="attachments-nav"><span class="nav-glyph">▤</span>Attachments</button>
|
<button class="label-link" id="attachments-nav"><span class="nav-glyph">▤</span>Attachments</button>
|
||||||
<div class="sidebar-divider"></div>
|
<div class="sidebar-divider"></div>
|
||||||
<div class="section-label"><span>LABELS</span><button class="tiny-plus" id="add-label" aria-label="Add label">+</button></div>
|
<div class="section-label"><span>LABELS</span><button class="tiny-plus" id="add-label" aria-label="Add label">+</button></div>
|
||||||
<button class="label-link" data-label="Design"><i class="label-dot dot-amber"></i>Design</button>
|
<button class="label-link" data-label="Design"><i class="label-dot dot-amber"></i>Design</button>
|
||||||
<button class="label-link" data-label="Travel"><i class="label-dot dot-blue"></i>Travel</button>
|
<button class="label-link" data-label="Travel"><i class="label-dot dot-blue"></i>Travel</button>
|
||||||
<button class="label-link" data-label="Personal"><i class="label-dot dot-green"></i>Personal</button>
|
<button class="label-link" data-label="Personal"><i class="label-dot dot-green"></i>Personal</button>
|
||||||
<div id="custom-labels"></div>
|
<div id="custom-labels"></div>
|
||||||
<div class="sidebar-bottom"><div class="storage"><div class="storage-top"><span>Storage</span><span>4.2 / 15 GB</span></div><div class="storage-bar"><i></i></div><small>Plenty of room for the good things.</small></div><button class="settings-button" id="settings-button"><span>⚙</span> Settings</button></div>
|
<div class="sidebar-bottom"><div class="storage"><div class="storage-top"><span>Storage</span><span>4.2 / 15 GB</span></div><div class="storage-bar"><i></i></div><small>Plenty of room for the good things.</small></div><button class="settings-button" id="settings-button"><span>⚙</span> Settings</button></div>
|
||||||
</aside>
|
</aside>
|
||||||
|
|
||||||
<main class="main-area">
|
<main class="main-area">
|
||||||
<header class="topbar"><div class="breadcrumbs"><span id="crumb-parent">Mail</span><span class="crumb-divider">/</span><strong id="crumb-current">Inbox</strong></div><div class="top-actions"><div class="search-wrap"><span>⌕</span><input id="search" placeholder="Search mail" aria-label="Search mail"><kbd>⌘ K</kbd></div><button class="icon-button" id="search-filters-toggle" aria-expanded="false" title="Search filters">☷</button><button class="icon-button help-button" aria-label="Help" title="Help">?</button><button class="avatar top-avatar profile-button" title="Account settings" aria-label="Account settings">•</button><section id="search-filters" class="search-filters hidden" aria-label="Advanced search filters"><label>Folder<select id="filter-folder"><option value="">Current folder</option><option>Inbox</option><option>Sent</option><option>Archive</option><option>Trash</option></select></label><label>From<input id="filter-sender" placeholder="Sender contains"></label><label>Subject<input id="filter-subject" placeholder="Subject contains"></label><label>After<input id="filter-after" type="date"></label><label>Before<input id="filter-before" type="date"></label><label class="filter-checkbox"><input id="filter-attachments" type="checkbox"> Has attachments</label><button id="clear-search-filters" class="text-button">Clear filters</button></section></div></header>
|
<header class="topbar"><div class="breadcrumbs"><span id="crumb-parent">Mail</span><span class="crumb-divider">/</span><strong id="crumb-current">Inbox</strong></div><div class="top-actions"><div class="search-wrap"><span>⌕</span><input id="search" placeholder="Search mail" aria-label="Search mail"><kbd>⌘ K</kbd></div><button class="icon-button" id="search-filters-toggle" aria-expanded="false" title="Search filters">☷</button><button class="icon-button help-button" aria-label="Help" title="Help">?</button><button class="avatar top-avatar profile-button" title="Account settings" aria-label="Account settings">•</button><section id="search-filters" class="search-filters hidden" aria-label="Advanced search filters"><label>Folder<select id="filter-folder"><option value="">Current folder</option><option>Inbox</option><option>Sent</option><option>Archive</option><option>Trash</option></select></label><label>From<input id="filter-sender" placeholder="Sender contains"></label><label>Subject<input id="filter-subject" placeholder="Subject contains"></label><label>After<input id="filter-after" type="date"></label><label>Before<input id="filter-before" type="date"></label><label class="filter-checkbox"><input id="filter-attachments" type="checkbox"> Has attachments</label><button id="clear-search-filters" class="text-button">Clear filters</button></section></div></header>
|
||||||
|
|
||||||
<section id="mail-view" class="content-view mail-layout">
|
<section id="mail-view" class="content-view mail-layout">
|
||||||
<div class="list-pane">
|
<div class="list-pane">
|
||||||
<div class="list-heading"><div><div class="date-line" id="today-label">MONDAY, OCTOBER 4</div><h2 id="welcome-heading">Good morning<span id="greeting-name" hidden></span></h2></div><button class="compose-button" id="compose"><span>+</span> Compose</button></div>
|
<div class="list-heading"><div><div class="date-line" id="today-label">MONDAY, OCTOBER 4</div><h2 id="welcome-heading">Good morning<span id="greeting-name" hidden></span></h2></div><button class="compose-button" id="compose"><span>+</span> Compose</button></div>
|
||||||
<div class="toolbar"><button class="tool-checkbox" id="select-all" aria-label="Select all">□</button><button class="icon-button" id="refresh" title="Refresh">↻</button><span class="toolbar-divider"></span><button class="icon-button" id="archive-selected" title="Archive">▱</button><button class="icon-button" id="delete-selected" title="Delete">⌫</button><button class="icon-button" id="mark-unread" title="Mark unread">✉</button><span class="toolbar-spacer"></span><button class="icon-button" id="previous-page" title="Previous page">‹</button><span class="pagination" id="pagination">1–8 of 24</span><button class="icon-button" id="next-page" title="Next page">›</button></div>
|
<div class="toolbar"><button class="tool-checkbox" id="select-all" aria-label="Select all">□</button><button class="icon-button" id="refresh" title="Refresh">↻</button><span class="toolbar-divider"></span><button class="icon-button" id="archive-selected" title="Archive">▱</button><button class="icon-button" id="delete-selected" title="Delete">⌫</button><button class="icon-button" id="mark-unread" title="Mark unread">✉</button><span class="toolbar-spacer"></span><button class="icon-button" id="previous-page" title="Previous page">‹</button><span class="pagination" id="pagination">1–8 of 24</span><button class="icon-button" id="next-page" title="Next page">›</button></div>
|
||||||
<div class="message-list" id="message-list" aria-label="Messages"></div>
|
<div class="message-list" id="message-list" aria-label="Messages"></div>
|
||||||
<div class="list-foot"><span><i class="online-dot"></i> <span id="mail-status">All caught up with your mail</span></span><button class="text-button" id="load-more">Load more <span>↓</span></button></div>
|
<div class="list-foot"><span><i class="online-dot"></i> <span id="mail-status">All caught up with your mail</span></span><button class="text-button" id="load-more">Load more <span>↓</span></button></div>
|
||||||
</div>
|
</div>
|
||||||
<article class="reader-pane" id="reader-pane"></article>
|
<article class="reader-pane" id="reader-pane"></article>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<section id="calendar-view" class="content-view page-view hidden"></section>
|
<section id="calendar-view" class="content-view page-view hidden"></section>
|
||||||
<section id="contacts-view" class="content-view page-view hidden"></section>
|
<section id="contacts-view" class="content-view page-view hidden"></section>
|
||||||
</main>
|
</main>
|
||||||
</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="renderer-state.js"></script>
|
||||||
@@ -70,13 +70,13 @@
|
|||||||
<script src="platform-bridge-loader.js"></script>
|
<script src="platform-bridge-loader.js"></script>
|
||||||
<script src="renderer-mail-api.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="dav-ui.js"></script>
|
<script src="dav-ui.js"></script>
|
||||||
<script src="account-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>
|
||||||
<script src="pgp-mail-ui.js"></script>
|
<script src="pgp-mail-ui.js"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" aria-hidden="true" focusable="false">
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" aria-hidden="true" focusable="false">
|
||||||
<g fill="none" stroke="#181b19">
|
<g fill="none" stroke="#181b19">
|
||||||
<circle cx="32" cy="32" r="28" stroke-width="2"/>
|
<circle cx="32" cy="32" r="28" stroke-width="2"/>
|
||||||
<path d="M32 3v58" stroke-width="3"/>
|
<path d="M32 3v58" stroke-width="3"/>
|
||||||
<ellipse cx="32" cy="18" rx="12" ry="5" stroke-width="2" transform="rotate(22 32 18)"/>
|
<ellipse cx="32" cy="18" rx="12" ry="5" stroke-width="2" transform="rotate(22 32 18)"/>
|
||||||
<ellipse cx="32" cy="46" rx="12" ry="5" stroke-width="2" transform="rotate(-22 32 46)"/>
|
<ellipse cx="32" cy="46" rx="12" ry="5" stroke-width="2" transform="rotate(-22 32 46)"/>
|
||||||
<ellipse cx="32" cy="32" rx="8" ry="8" stroke-width="1.5" opacity=".6" transform="rotate(45 32 32)"/>
|
<ellipse cx="32" cy="32" rx="8" ry="8" stroke-width="1.5" opacity=".6" transform="rotate(45 32 32)"/>
|
||||||
</g>
|
</g>
|
||||||
</svg>
|
</svg>
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 534 B After Width: | Height: | Size: 543 B |
@@ -1,9 +1,9 @@
|
|||||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" aria-hidden="true" focusable="false">
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" aria-hidden="true" focusable="false">
|
||||||
<g fill="none" stroke="#e7e2d3">
|
<g fill="none" stroke="#e7e2d3">
|
||||||
<circle cx="32" cy="32" r="28" stroke-width="2"/>
|
<circle cx="32" cy="32" r="28" stroke-width="2"/>
|
||||||
<path d="M32 3v58" stroke-width="3"/>
|
<path d="M32 3v58" stroke-width="3"/>
|
||||||
<ellipse cx="32" cy="18" rx="12" ry="5" stroke-width="2" transform="rotate(22 32 18)"/>
|
<ellipse cx="32" cy="18" rx="12" ry="5" stroke-width="2" transform="rotate(22 32 18)"/>
|
||||||
<ellipse cx="32" cy="46" rx="12" ry="5" stroke-width="2" transform="rotate(-22 32 46)"/>
|
<ellipse cx="32" cy="46" rx="12" ry="5" stroke-width="2" transform="rotate(-22 32 46)"/>
|
||||||
<ellipse cx="32" cy="32" rx="8" ry="8" stroke-width="1.5" opacity=".6" transform="rotate(45 32 32)"/>
|
<ellipse cx="32" cy="32" rx="8" ry="8" stroke-width="1.5" opacity=".6" transform="rotate(45 32 32)"/>
|
||||||
</g>
|
</g>
|
||||||
</svg>
|
</svg>
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 534 B After Width: | Height: | Size: 543 B |
@@ -1,10 +1,10 @@
|
|||||||
{
|
{
|
||||||
"name": "ep-mail",
|
"name": "ep-mail",
|
||||||
"short_name": "ep-mail",
|
"short_name": "ep-mail",
|
||||||
"description": "Eternity Project mail, calendar, and contacts.",
|
"description": "Eternity Project mail, calendar, and contacts.",
|
||||||
"start_url": "./",
|
"start_url": "./",
|
||||||
"display": "standalone",
|
"display": "standalone",
|
||||||
"background_color": "#f4f5f1",
|
"background_color": "#f4f5f1",
|
||||||
"theme_color": "#f4f5f1",
|
"theme_color": "#f4f5f1",
|
||||||
"icons": [{"src":"icon.svg","sizes":"any","type":"image/svg+xml","purpose":"any maskable"}]
|
"icons": [{"src":"icon.svg","sizes":"any","type":"image/svg+xml","purpose":"any maskable"}]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,193 +6,193 @@ const selectAllPgpMailUi = pgpMailUi.selectAll;
|
|||||||
const toastPgpMailUi = pgpMailUi.toast;
|
const toastPgpMailUi = pgpMailUi.toast;
|
||||||
const escapePgpMailUi = pgpMailUi.escapeHtml;
|
const escapePgpMailUi = pgpMailUi.escapeHtml;
|
||||||
const pgpApi = () => window.daybreakMail?.pgp;
|
const pgpApi = () => window.daybreakMail?.pgp;
|
||||||
|
|
||||||
function pgpAskPassphrase(title, detail) {
|
function pgpAskPassphrase(title, detail) {
|
||||||
return new Promise(resolve => {
|
return new Promise(resolve => {
|
||||||
const overlay = document.createElement('div');
|
const overlay = document.createElement('div');
|
||||||
overlay.className = 'modal-overlay pgp-prompt';
|
overlay.className = 'modal-overlay pgp-prompt';
|
||||||
overlay.innerHTML = `<form class="compose-modal pgp-prompt-box" autocomplete="off"><div class="modal-head"><span></span></div><div class="compose-fields"><p class="account-note"></p><label class="compose-line"><span>Passphrase</span><input type="password" id="pgp-prompt-input" autocomplete="current-password"></label></div><div class="compose-footer"><button type="button" class="discard" data-cancel>Cancel</button><button type="submit" class="send-button">Unlock</button></div></form>`;
|
overlay.innerHTML = `<form class="compose-modal pgp-prompt-box" autocomplete="off"><div class="modal-head"><span></span></div><div class="compose-fields"><p class="account-note"></p><label class="compose-line"><span>Passphrase</span><input type="password" id="pgp-prompt-input" autocomplete="current-password"></label></div><div class="compose-footer"><button type="button" class="discard" data-cancel>Cancel</button><button type="submit" class="send-button">Unlock</button></div></form>`;
|
||||||
overlay.querySelector('.modal-head span').textContent = title;
|
overlay.querySelector('.modal-head span').textContent = title;
|
||||||
overlay.querySelector('.account-note').textContent = detail;
|
overlay.querySelector('.account-note').textContent = detail;
|
||||||
const finish = value => { overlay.remove(); resolve(value); };
|
const finish = value => { overlay.remove(); resolve(value); };
|
||||||
overlay.querySelector('form').onsubmit = event => {
|
overlay.querySelector('form').onsubmit = event => {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
const value = overlay.querySelector('input').value;
|
const value = overlay.querySelector('input').value;
|
||||||
if (value) finish(value);
|
if (value) finish(value);
|
||||||
};
|
};
|
||||||
overlay.querySelector('[data-cancel]').onclick = () => finish(null);
|
overlay.querySelector('[data-cancel]').onclick = () => finish(null);
|
||||||
overlay.addEventListener('keydown', event => { if (event.key === 'Escape') { event.stopPropagation(); finish(null); } });
|
overlay.addEventListener('keydown', event => { if (event.key === 'Escape') { event.stopPropagation(); finish(null); } });
|
||||||
document.body.append(overlay);
|
document.body.append(overlay);
|
||||||
overlay.querySelector('input').focus();
|
overlay.querySelector('input').focus();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function pgpFormatFingerprint(value) {
|
function pgpFormatFingerprint(value) {
|
||||||
return String(value || '').match(/.{1,4}/g)?.join(' ') || '';
|
return String(value || '').match(/.{1,4}/g)?.join(' ') || '';
|
||||||
}
|
}
|
||||||
|
|
||||||
function pgpSignatureHtml(signatures, encrypted) {
|
function pgpSignatureHtml(signatures, encrypted) {
|
||||||
const items = Array.isArray(signatures) ? signatures : [];
|
const items = Array.isArray(signatures) ? signatures : [];
|
||||||
const lock = encrypted ? '🔒 Encrypted. ' : '';
|
const lock = encrypted ? '🔒 Encrypted. ' : '';
|
||||||
if (!items.length) {
|
if (!items.length) {
|
||||||
return encrypted ? `<section class="pgp-status pgp-warn" role="status"><strong>${lock}Not signed</strong><span>The sender is not authenticated: anyone with your public key could have written this.</span></section>` : '';
|
return encrypted ? `<section class="pgp-status pgp-warn" role="status"><strong>${lock}Not signed</strong><span>The sender is not authenticated: anyone with your public key could have written this.</span></section>` : '';
|
||||||
}
|
}
|
||||||
return items.map(signature => {
|
return items.map(signature => {
|
||||||
const trust = signature.trust === 'verified' ? 'verified key' : signature.trust === 'trusted' ? 'trusted key' : 'key not verified yet';
|
const trust = signature.trust === 'verified' ? 'verified key' : signature.trust === 'trusted' ? 'trusted key' : 'key not verified yet';
|
||||||
const notes = [];
|
const notes = [];
|
||||||
if (signature.keyChanged) notes.push('The sender previously used a different key. Confirm the change with them before trusting this message.');
|
if (signature.keyChanged) notes.push('The sender previously used a different key. Confirm the change with them before trusting this message.');
|
||||||
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 ${escapePgpMailUi(signature.email || 'a known key')}</strong><span>${escapePgpMailUi(trust)} · ${escapePgpMailUi(pgpFormatFingerprint(signature.fingerprint))}</span>${notes.map(note => `<small>${escapePgpMailUi(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 ${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-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('');
|
||||||
}
|
}
|
||||||
|
|
||||||
async function pgpAddAttachedKey(key) {
|
async function pgpAddAttachedKey(key) {
|
||||||
const emails = key.emails.join(', ') || 'unknown address';
|
const emails = key.emails.join(', ') || 'unknown address';
|
||||||
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' });
|
||||||
toastPgpMailUi(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) {
|
||||||
toastPgpMailUi(error.message || 'Could not add the key');
|
toastPgpMailUi(error.message || 'Could not add the key');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function pgpRenderReaderState(message) {
|
function pgpRenderReaderState(message) {
|
||||||
const reader = selectPgpMailUi('#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());
|
||||||
let html = '';
|
let html = '';
|
||||||
if (message.encrypted && !message.pgpDecrypted) {
|
if (message.encrypted && !message.pgpDecrypted) {
|
||||||
html = `<section class="pgp-banner" role="status"><strong>🔒 This message is encrypted</strong><span id="pgp-banner-text">Unlock it with your key passphrase to read it.</span><button type="button" class="send-button" id="pgp-unlock">Unlock</button></section>`;
|
html = `<section class="pgp-banner" role="status"><strong>🔒 This message is encrypted</strong><span id="pgp-banner-text">Unlock it with your key passphrase to read it.</span><button type="button" class="send-button" id="pgp-unlock">Unlock</button></section>`;
|
||||||
} else if (message.encrypted) {
|
} else if (message.encrypted) {
|
||||||
html = pgpSignatureHtml(message.pgpResult?.signatures, true);
|
html = pgpSignatureHtml(message.pgpResult?.signatures, true);
|
||||||
} else if (message.pgpSignatures) {
|
} else if (message.pgpSignatures) {
|
||||||
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>${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(''));
|
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 = selectPgpMailUi('#pgp-unlock');
|
const unlock = selectPgpMailUi('#pgp-unlock');
|
||||||
if (unlock) unlock.onclick = () => pgpUnlockMessage(message, true);
|
if (unlock) unlock.onclick = () => pgpUnlockMessage(message, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function pgpUnlockMessage(message, interactive) {
|
async function pgpUnlockMessage(message, interactive) {
|
||||||
let passphrase = null;
|
let passphrase = null;
|
||||||
for (let attempt = 0; attempt < 3; attempt += 1) {
|
for (let attempt = 0; attempt < 3; attempt += 1) {
|
||||||
let result;
|
let result;
|
||||||
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) {
|
||||||
toastPgpMailUi(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, html: result.html, 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 (pgpMailUi.state.activeMessage === message.id) pgpMailUi.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') {
|
||||||
if (!interactive) { pgpRenderReaderState(message); return; }
|
if (!interactive) { pgpRenderReaderState(message); return; }
|
||||||
passphrase = await pgpAskPassphrase('Unlock encrypted message', result.code === 'BAD_PASSPHRASE' ? 'That passphrase was incorrect. Try again.' : `Enter the passphrase for ${result.email || 'your key'}.`);
|
passphrase = await pgpAskPassphrase('Unlock encrypted message', result.code === 'BAD_PASSPHRASE' ? 'That passphrase was incorrect. Try again.' : `Enter the passphrase for ${result.email || 'your key'}.`);
|
||||||
if (passphrase === null) return;
|
if (passphrase === null) return;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
const text = selectPgpMailUi('#pgp-banner-text');
|
const text = selectPgpMailUi('#pgp-banner-text');
|
||||||
if (text) text.textContent = result.message;
|
if (text) text.textContent = result.message;
|
||||||
else toastPgpMailUi(result.message);
|
else toastPgpMailUi(result.message);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pgpMailUi.wrapOpenMessage(baseOpenMessage => function (id) {
|
pgpMailUi.wrapOpenMessage(baseOpenMessage => function (id) {
|
||||||
baseOpenMessage(id);
|
baseOpenMessage(id);
|
||||||
const message = pgpMailUi.state.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.
|
||||||
pgpMailUi.wrapShowCompose(baseShowCompose => function (reply, forward = false) {
|
pgpMailUi.wrapShowCompose(baseShowCompose => function (reply, forward = false) {
|
||||||
baseShowCompose(reply, forward);
|
baseShowCompose(reply, forward);
|
||||||
const footer = selectPgpMailUi('#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 = selectPgpMailUi('#pgp-encrypt');
|
const encrypt = selectPgpMailUi('#pgp-encrypt');
|
||||||
const sign = selectPgpMailUi('#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 = selectPgpMailUi('#compose-to')?.value || '';
|
const to = selectPgpMailUi('#compose-to')?.value || '';
|
||||||
const cc = selectPgpMailUi('#compose-cc')?.value || '';
|
const cc = selectPgpMailUi('#compose-cc')?.value || '';
|
||||||
const hint = selectPgpMailUi('#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 (!selectPgpMailUi('#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';
|
||||||
if (!touched && !encrypt.checked) encrypt.checked = true;
|
if (!touched && !encrypt.checked) encrypt.checked = true;
|
||||||
}
|
}
|
||||||
} 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 => selectPgpMailUi(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.
|
||||||
async function prepareSend(to, cc) {
|
async function prepareSend(to, cc) {
|
||||||
if (!pgpApi()) return null;
|
if (!pgpApi()) return null;
|
||||||
let encrypt = Boolean(selectPgpMailUi('#pgp-encrypt')?.checked);
|
let encrypt = Boolean(selectPgpMailUi('#pgp-encrypt')?.checked);
|
||||||
const sign = Boolean(selectPgpMailUi('#pgp-sign')?.checked);
|
const sign = Boolean(selectPgpMailUi('#pgp-sign')?.checked);
|
||||||
if (!encrypt && !sign && selectPgpMailUi('#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 && selectPgpMailUi('#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;
|
||||||
}
|
}
|
||||||
if (!encrypt && !sign) return null;
|
if (!encrypt && !sign) return null;
|
||||||
if (encrypt && status.missing.length) {
|
if (encrypt && status.missing.length) {
|
||||||
const sendPlain = confirm(`No public key for ${status.missing.join(', ')}.\n\nThe message cannot be encrypted for everyone. Send it WITHOUT encryption?`);
|
const sendPlain = confirm(`No public key for ${status.missing.join(', ')}.\n\nThe message cannot be encrypted for everyone. Send it WITHOUT encryption?`);
|
||||||
if (!sendPlain) return false;
|
if (!sendPlain) return false;
|
||||||
encrypt = false;
|
encrypt = false;
|
||||||
if (!sign) return null;
|
if (!sign) return null;
|
||||||
}
|
}
|
||||||
let passphrase = null;
|
let passphrase = null;
|
||||||
if (sign) {
|
if (sign) {
|
||||||
if (!status.signer) { toastPgpMailUi('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 };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,418 +6,418 @@ const selectAllPgpKeyUi = pgpKeyMailUi.selectAll;
|
|||||||
const escapePgpKeyUi = pgpKeyMailUi.escapeHtml;
|
const escapePgpKeyUi = pgpKeyMailUi.escapeHtml;
|
||||||
const toastPgpKeyUi = pgpKeyMailUi.toast;
|
const toastPgpKeyUi = pgpKeyMailUi.toast;
|
||||||
function pgpAvailable() { return Boolean(window.daybreakMail?.pgp); }
|
function pgpAvailable() { return Boolean(window.daybreakMail?.pgp); }
|
||||||
|
|
||||||
function openEncryptionKeys() {
|
function openEncryptionKeys() {
|
||||||
const root = selectPgpKeyUi('#modal-root');
|
const root = selectPgpKeyUi('#modal-root');
|
||||||
const account = window.epMailFeatures.mail.connectedAccount || {};
|
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>
|
<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>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>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>
|
<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>
|
<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>
|
<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>
|
<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>
|
<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>
|
<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 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>
|
<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>
|
<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>
|
<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>
|
<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>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>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>
|
<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>
|
<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="${escapePgpKeyUi(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="${escapePgpKeyUi(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>
|
||||||
</div></div></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 status = message => { selectPgpKeyUi('#pgp-status').textContent = message; };
|
const status = message => { selectPgpKeyUi('#pgp-status').textContent = message; };
|
||||||
const passphraseField = () => selectPgpKeyUi('#pgp-passphrase');
|
const passphraseField = () => selectPgpKeyUi('#pgp-passphrase');
|
||||||
let keyServers = [];
|
let keyServers = [];
|
||||||
const selectedPublishServer = () => keyServers.find(server => server.id === selectPgpKeyUi('#pgp-publish-server').value && server.enabled);
|
const selectedPublishServer = () => keyServers.find(server => server.id === selectPgpKeyUi('#pgp-publish-server').value && server.enabled);
|
||||||
const updatePublishButtons = () => {
|
const updatePublishButtons = () => {
|
||||||
const server = selectedPublishServer();
|
const server = selectedPublishServer();
|
||||||
selectAllPgpKeyUi('.pgp-publish').forEach(button => {
|
selectAllPgpKeyUi('.pgp-publish').forEach(button => {
|
||||||
button.disabled = !server;
|
button.disabled = !server;
|
||||||
button.textContent = server ? `Publish to ${server.name}…` : 'Enable a server to publish…';
|
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(); }
|
||||||
return value;
|
return value;
|
||||||
};
|
};
|
||||||
|
|
||||||
async function render() {
|
async function render() {
|
||||||
const list = selectPgpKeyUi('#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();
|
||||||
if (!keys.length) { list.textContent = 'No keys yet.'; return; }
|
if (!keys.length) { list.textContent = 'No keys yet.'; return; }
|
||||||
keys.forEach(key => {
|
keys.forEach(key => {
|
||||||
const row = document.createElement('div');
|
const row = document.createElement('div');
|
||||||
row.className = 'attachment-row';
|
row.className = 'attachment-row';
|
||||||
const info = document.createElement('div');
|
const info = document.createElement('div');
|
||||||
info.className = 'attachment-row-info';
|
info.className = 'attachment-row-info';
|
||||||
const title = document.createElement('strong');
|
const title = document.createElement('strong');
|
||||||
title.textContent = key.email || 'OpenPGP key';
|
title.textContent = key.email || 'OpenPGP key';
|
||||||
const meta = document.createElement('small');
|
const meta = document.createElement('small');
|
||||||
meta.textContent = `${key.name ? key.name + ' · ' : ''}${key.algorithm} · ${new Date(key.createdAt).toLocaleDateString()}`;
|
meta.textContent = `${key.name ? key.name + ' · ' : ''}${key.algorithm} · ${new Date(key.createdAt).toLocaleDateString()}`;
|
||||||
const fingerprint = document.createElement('small');
|
const fingerprint = document.createElement('small');
|
||||||
fingerprint.textContent = `Fingerprint: ${key.fingerprint.match(/.{1,4}/g).join(' ')}`;
|
fingerprint.textContent = `Fingerprint: ${key.fingerprint.match(/.{1,4}/g).join(' ')}`;
|
||||||
info.append(title, meta, fingerprint);
|
info.append(title, meta, fingerprint);
|
||||||
row.append(info);
|
row.append(info);
|
||||||
const actions = [
|
const actions = [
|
||||||
['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');
|
const changePassphrase = document.createElement('button');
|
||||||
changePassphrase.className = 'discard';
|
changePassphrase.className = 'discard';
|
||||||
changePassphrase.textContent = 'Change passphrase…';
|
changePassphrase.textContent = 'Change passphrase…';
|
||||||
changePassphrase.onclick = async () => {
|
changePassphrase.onclick = async () => {
|
||||||
const currentPassphrase = selectPgpKeyUi('#pgp-change-current-passphrase').value;
|
const currentPassphrase = selectPgpKeyUi('#pgp-change-current-passphrase').value;
|
||||||
if (!currentPassphrase) {
|
if (!currentPassphrase) {
|
||||||
status('Enter the current passphrase for this key.');
|
status('Enter the current passphrase for this key.');
|
||||||
selectPgpKeyUi('#pgp-change-current-passphrase').focus();
|
selectPgpKeyUi('#pgp-change-current-passphrase').focus();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const newPassphrase = selectPgpKeyUi('#pgp-new-passphrase').value;
|
const newPassphrase = selectPgpKeyUi('#pgp-new-passphrase').value;
|
||||||
if (newPassphrase.length < 8) {
|
if (newPassphrase.length < 8) {
|
||||||
status('Use a new passphrase of at least 8 characters.');
|
status('Use a new passphrase of at least 8 characters.');
|
||||||
selectPgpKeyUi('#pgp-new-passphrase').focus();
|
selectPgpKeyUi('#pgp-new-passphrase').focus();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (newPassphrase !== selectPgpKeyUi('#pgp-confirm-passphrase').value) {
|
if (newPassphrase !== selectPgpKeyUi('#pgp-confirm-passphrase').value) {
|
||||||
status('The new passphrases do not match.');
|
status('The new passphrases do not match.');
|
||||||
selectPgpKeyUi('#pgp-confirm-passphrase').focus();
|
selectPgpKeyUi('#pgp-confirm-passphrase').focus();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
changePassphrase.disabled = true;
|
changePassphrase.disabled = true;
|
||||||
try {
|
try {
|
||||||
await window.daybreakMail.pgp.changePassphrase({
|
await window.daybreakMail.pgp.changePassphrase({
|
||||||
fingerprint: key.fingerprint,
|
fingerprint: key.fingerprint,
|
||||||
currentPassphrase,
|
currentPassphrase,
|
||||||
newPassphrase
|
newPassphrase
|
||||||
});
|
});
|
||||||
selectPgpKeyUi('#pgp-change-current-passphrase').value = '';
|
selectPgpKeyUi('#pgp-change-current-passphrase').value = '';
|
||||||
status(`Passphrase changed for ${key.email || key.fingerprint}.`);
|
status(`Passphrase changed for ${key.email || key.fingerprint}.`);
|
||||||
} catch (error) { status(error.message || 'Could not change the key passphrase.'); }
|
} catch (error) { status(error.message || 'Could not change the key passphrase.'); }
|
||||||
finally {
|
finally {
|
||||||
selectPgpKeyUi('#pgp-new-passphrase').value = '';
|
selectPgpKeyUi('#pgp-new-passphrase').value = '';
|
||||||
selectPgpKeyUi('#pgp-confirm-passphrase').value = '';
|
selectPgpKeyUi('#pgp-confirm-passphrase').value = '';
|
||||||
changePassphrase.disabled = false;
|
changePassphrase.disabled = false;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
row.append(changePassphrase);
|
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 };
|
||||||
await window.daybreakMail.pgp.remove(key.fingerprint, needPassphrase());
|
await window.daybreakMail.pgp.remove(key.fingerprint, needPassphrase());
|
||||||
await render();
|
await render();
|
||||||
return { deleted: true };
|
return { deleted: true };
|
||||||
}, true]);
|
}, true]);
|
||||||
actions.forEach(([label, run, secret]) => {
|
actions.forEach(([label, run, secret]) => {
|
||||||
const button = document.createElement('button');
|
const button = document.createElement('button');
|
||||||
button.className = 'discard';
|
button.className = 'discard';
|
||||||
button.textContent = label;
|
button.textContent = label;
|
||||||
button.onclick = async () => {
|
button.onclick = async () => {
|
||||||
if (secret && !passphraseField().value) { needPassphrase(); return; }
|
if (secret && !passphraseField().value) { needPassphrase(); return; }
|
||||||
try {
|
try {
|
||||||
const result = await run();
|
const result = await run();
|
||||||
status(result?.saved ? 'File saved.' : result?.deleted ? 'Key deleted.' : '');
|
status(result?.saved ? 'File saved.' : result?.deleted ? 'Key deleted.' : '');
|
||||||
} catch (error) { status(error.message || 'That action failed.'); }
|
} catch (error) { status(error.message || 'That action failed.'); }
|
||||||
};
|
};
|
||||||
row.append(button);
|
row.append(button);
|
||||||
});
|
});
|
||||||
const publish = document.createElement('button');
|
const publish = document.createElement('button');
|
||||||
publish.className = 'discard pgp-publish';
|
publish.className = 'discard pgp-publish';
|
||||||
publish.onclick = async () => {
|
publish.onclick = async () => {
|
||||||
const server = selectedPublishServer();
|
const server = selectedPublishServer();
|
||||||
if (!server) { status('Enable a key server and select it as the publication target first.'); return; }
|
if (!server) { status('Enable a key server and select it as the publication target first.'); return; }
|
||||||
publish.disabled = true;
|
publish.disabled = true;
|
||||||
try {
|
try {
|
||||||
const result = await window.daybreakMail.pgp.publishKey({ fingerprint: key.fingerprint, serverId: server.id });
|
const result = await window.daybreakMail.pgp.publishKey({ fingerprint: key.fingerprint, serverId: server.id });
|
||||||
if (result.canceled) return;
|
if (result.canceled) return;
|
||||||
if (result.warning) status(result.warning);
|
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 === '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 === '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 === '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 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());
|
else status(`${server.name} accepted the key. ${result.message || ''}`.trim());
|
||||||
} catch (error) { status(error.message || 'Could not publish the public key.'); }
|
} catch (error) { status(error.message || 'Could not publish the public key.'); }
|
||||||
finally { updatePublishButtons(); }
|
finally { updatePublishButtons(); }
|
||||||
};
|
};
|
||||||
row.append(publish);
|
row.append(publish);
|
||||||
list.append(row);
|
list.append(row);
|
||||||
});
|
});
|
||||||
updatePublishButtons();
|
updatePublishButtons();
|
||||||
}
|
}
|
||||||
|
|
||||||
selectPgpKeyUi('#pgp-generate').onclick = async () => {
|
selectPgpKeyUi('#pgp-generate').onclick = async () => {
|
||||||
const button = selectPgpKeyUi('#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: selectPgpKeyUi('#pgp-name').value, email: selectPgpKeyUi('#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;
|
||||||
};
|
};
|
||||||
selectPgpKeyUi('#pgp-import').onclick = async () => {
|
selectPgpKeyUi('#pgp-import').onclick = async () => {
|
||||||
const passphrase = needPassphrase();
|
const passphrase = needPassphrase();
|
||||||
if (!passphrase) return;
|
if (!passphrase) return;
|
||||||
try {
|
try {
|
||||||
const result = await window.daybreakMail.pgp.importKey({ passphrase, accountId: account.id || null });
|
const result = await window.daybreakMail.pgp.importKey({ passphrase, accountId: account.id || null });
|
||||||
status(result.canceled ? '' : 'Key imported.');
|
status(result.canceled ? '' : 'Key imported.');
|
||||||
await render();
|
await render();
|
||||||
} 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 = selectPgpKeyUi('#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();
|
||||||
if (!contacts.length) { list.textContent = 'No contact keys yet. Import a public key, or add one from a received message.'; return; }
|
if (!contacts.length) { list.textContent = 'No contact keys yet. Import a public key, or add one from a received message.'; return; }
|
||||||
contacts.forEach(contact => {
|
contacts.forEach(contact => {
|
||||||
const row = document.createElement('div');
|
const row = document.createElement('div');
|
||||||
row.className = 'attachment-row';
|
row.className = 'attachment-row';
|
||||||
const info = document.createElement('div');
|
const info = document.createElement('div');
|
||||||
info.className = 'attachment-row-info';
|
info.className = 'attachment-row-info';
|
||||||
const title = document.createElement('strong');
|
const title = document.createElement('strong');
|
||||||
title.textContent = contact.emails.join(', ') || contact.name || 'Public key';
|
title.textContent = contact.emails.join(', ') || contact.name || 'Public key';
|
||||||
const meta = document.createElement('small');
|
const meta = document.createElement('small');
|
||||||
meta.textContent = `${contact.name ? contact.name + ' · ' : ''}added ${new Date(contact.addedAt).toLocaleDateString()} · from ${contact.source}`;
|
meta.textContent = `${contact.name ? contact.name + ' · ' : ''}added ${new Date(contact.addedAt).toLocaleDateString()} · from ${contact.source}`;
|
||||||
const fingerprint = document.createElement('small');
|
const fingerprint = document.createElement('small');
|
||||||
fingerprint.textContent = `Fingerprint: ${contact.fingerprint.match(/.{1,4}/g).join(' ')}`;
|
fingerprint.textContent = `Fingerprint: ${contact.fingerprint.match(/.{1,4}/g).join(' ')}`;
|
||||||
info.append(title, meta, fingerprint);
|
info.append(title, meta, fingerprint);
|
||||||
const trust = document.createElement('select');
|
const trust = document.createElement('select');
|
||||||
trust.className = 'pgp-trust';
|
trust.className = 'pgp-trust';
|
||||||
trust.setAttribute('aria-label', 'Key trust');
|
trust.setAttribute('aria-label', 'Key trust');
|
||||||
[['unknown', 'Not verified'], ['trusted', 'Trusted'], ['verified', 'Verified (fingerprint checked)']].forEach(([value, label]) => {
|
[['unknown', 'Not verified'], ['trusted', 'Trusted'], ['verified', 'Verified (fingerprint checked)']].forEach(([value, label]) => {
|
||||||
const option = document.createElement('option');
|
const option = document.createElement('option');
|
||||||
option.value = value; option.textContent = label; option.selected = contact.trust === value;
|
option.value = value; option.textContent = label; option.selected = contact.trust === value;
|
||||||
trust.append(option);
|
trust.append(option);
|
||||||
});
|
});
|
||||||
trust.onchange = async () => {
|
trust.onchange = async () => {
|
||||||
if (trust.value === 'verified' && !confirm(`Mark this key as verified only if you compared this fingerprint with its owner through another channel:\n\n${contact.fingerprint.match(/.{1,4}/g).join(' ')}`)) {
|
if (trust.value === 'verified' && !confirm(`Mark this key as verified only if you compared this fingerprint with its owner through another channel:\n\n${contact.fingerprint.match(/.{1,4}/g).join(' ')}`)) {
|
||||||
trust.value = contact.trust;
|
trust.value = contact.trust;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
try { await window.daybreakMail.pgp.setTrust(contact.fingerprint, trust.value); contact.trust = trust.value; status('Trust updated.'); }
|
try { await window.daybreakMail.pgp.setTrust(contact.fingerprint, trust.value); contact.trust = trust.value; status('Trust updated.'); }
|
||||||
catch (error) { trust.value = contact.trust; status(error.message || 'Could not update trust.'); }
|
catch (error) { trust.value = contact.trust; status(error.message || 'Could not update trust.'); }
|
||||||
};
|
};
|
||||||
const actions = [
|
const actions = [
|
||||||
['Export', () => window.daybreakMail.pgp.exportContact(contact.fingerprint)],
|
['Export', () => window.daybreakMail.pgp.exportContact(contact.fingerprint)],
|
||||||
['Remove', async () => {
|
['Remove', async () => {
|
||||||
if (!confirm('Remove this contact key? You will no longer be able to encrypt to it.')) return { canceled: true };
|
if (!confirm('Remove this contact key? You will no longer be able to encrypt to it.')) return { canceled: true };
|
||||||
await window.daybreakMail.pgp.removeContact(contact.fingerprint);
|
await window.daybreakMail.pgp.removeContact(contact.fingerprint);
|
||||||
await renderContacts();
|
await renderContacts();
|
||||||
return { deleted: true };
|
return { deleted: true };
|
||||||
}]
|
}]
|
||||||
];
|
];
|
||||||
row.append(info, trust);
|
row.append(info, trust);
|
||||||
actions.forEach(([label, run]) => {
|
actions.forEach(([label, run]) => {
|
||||||
const button = document.createElement('button');
|
const button = document.createElement('button');
|
||||||
button.className = 'discard';
|
button.className = 'discard';
|
||||||
button.textContent = label;
|
button.textContent = label;
|
||||||
button.onclick = async () => {
|
button.onclick = async () => {
|
||||||
try { const result = await run(); status(result?.saved ? 'File saved.' : result?.deleted ? 'Contact key removed.' : ''); }
|
try { const result = await run(); status(result?.saved ? 'File saved.' : result?.deleted ? 'Contact key removed.' : ''); }
|
||||||
catch (error) { status(error.message || 'That action failed.'); }
|
catch (error) { status(error.message || 'That action failed.'); }
|
||||||
};
|
};
|
||||||
row.append(button);
|
row.append(button);
|
||||||
});
|
});
|
||||||
list.append(row);
|
list.append(row);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
selectPgpKeyUi('#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.'); }
|
||||||
};
|
};
|
||||||
async function renderKeyServers() {
|
async function renderKeyServers() {
|
||||||
const list = selectPgpKeyUi('#pgp-server-list');
|
const list = selectPgpKeyUi('#pgp-server-list');
|
||||||
const selector = selectPgpKeyUi('#pgp-publish-server');
|
const selector = selectPgpKeyUi('#pgp-publish-server');
|
||||||
const selectedId = selector.value;
|
const selectedId = selector.value;
|
||||||
try { keyServers = await window.daybreakMail.pgp.keyServers(); }
|
try { keyServers = await window.daybreakMail.pgp.keyServers(); }
|
||||||
catch (error) { list.textContent = error.message || 'Could not load key servers.'; return; }
|
catch (error) { list.textContent = error.message || 'Could not load key servers.'; return; }
|
||||||
selector.replaceChildren();
|
selector.replaceChildren();
|
||||||
const enabledServers = keyServers.filter(server => server.enabled);
|
const enabledServers = keyServers.filter(server => server.enabled);
|
||||||
if (!enabledServers.length) {
|
if (!enabledServers.length) {
|
||||||
const option = document.createElement('option');
|
const option = document.createElement('option');
|
||||||
option.value = '';
|
option.value = '';
|
||||||
option.textContent = 'No enabled servers';
|
option.textContent = 'No enabled servers';
|
||||||
selector.append(option);
|
selector.append(option);
|
||||||
} else enabledServers.forEach(server => {
|
} else enabledServers.forEach(server => {
|
||||||
const option = document.createElement('option');
|
const option = document.createElement('option');
|
||||||
option.value = server.id;
|
option.value = server.id;
|
||||||
option.textContent = `${server.name} (${server.protocol.toUpperCase()})`;
|
option.textContent = `${server.name} (${server.protocol.toUpperCase()})`;
|
||||||
option.selected = server.id === selectedId;
|
option.selected = server.id === selectedId;
|
||||||
selector.append(option);
|
selector.append(option);
|
||||||
});
|
});
|
||||||
if (selectedId && !enabledServers.some(server => server.id === selectedId)) selector.selectedIndex = 0;
|
if (selectedId && !enabledServers.some(server => server.id === selectedId)) selector.selectedIndex = 0;
|
||||||
selector.onchange = updatePublishButtons;
|
selector.onchange = updatePublishButtons;
|
||||||
list.replaceChildren();
|
list.replaceChildren();
|
||||||
keyServers.forEach(server => {
|
keyServers.forEach(server => {
|
||||||
const row = document.createElement('div');
|
const row = document.createElement('div');
|
||||||
row.className = 'attachment-row';
|
row.className = 'attachment-row';
|
||||||
const info = document.createElement('div');
|
const info = document.createElement('div');
|
||||||
info.className = 'attachment-row-info';
|
info.className = 'attachment-row-info';
|
||||||
const title = document.createElement('strong');
|
const title = document.createElement('strong');
|
||||||
title.textContent = server.name;
|
title.textContent = server.name;
|
||||||
const details = document.createElement('small');
|
const details = document.createElement('small');
|
||||||
details.textContent = `${server.protocol.toUpperCase()} · ${server.url}${server.builtin ? ' · built in' : ' · custom'}`;
|
details.textContent = `${server.protocol.toUpperCase()} · ${server.url}${server.builtin ? ' · built in' : ' · custom'}`;
|
||||||
info.append(title, details);
|
info.append(title, details);
|
||||||
const enabledLabel = document.createElement('label');
|
const enabledLabel = document.createElement('label');
|
||||||
enabledLabel.className = 'compose-line';
|
enabledLabel.className = 'compose-line';
|
||||||
const enabledText = document.createElement('span');
|
const enabledText = document.createElement('span');
|
||||||
enabledText.textContent = 'Use for lookup and publishing';
|
enabledText.textContent = 'Use for lookup and publishing';
|
||||||
const enabled = document.createElement('input');
|
const enabled = document.createElement('input');
|
||||||
enabled.type = 'checkbox';
|
enabled.type = 'checkbox';
|
||||||
enabled.checked = server.enabled;
|
enabled.checked = server.enabled;
|
||||||
enabled.setAttribute('aria-label', `${server.name} enabled`);
|
enabled.setAttribute('aria-label', `${server.name} enabled`);
|
||||||
enabled.onchange = async () => {
|
enabled.onchange = async () => {
|
||||||
enabled.disabled = true;
|
enabled.disabled = true;
|
||||||
try {
|
try {
|
||||||
await window.daybreakMail.pgp.setKeyServerEnabled(server.id, enabled.checked);
|
await window.daybreakMail.pgp.setKeyServerEnabled(server.id, enabled.checked);
|
||||||
await renderKeyServers();
|
await renderKeyServers();
|
||||||
status(`${server.name} ${enabled.checked ? 'enabled' : 'disabled'}.`);
|
status(`${server.name} ${enabled.checked ? 'enabled' : 'disabled'}.`);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
enabled.checked = server.enabled;
|
enabled.checked = server.enabled;
|
||||||
status(error.message || `Could not update ${server.name}.`);
|
status(error.message || `Could not update ${server.name}.`);
|
||||||
} finally { enabled.disabled = false; }
|
} finally { enabled.disabled = false; }
|
||||||
};
|
};
|
||||||
enabledLabel.append(enabledText, enabled);
|
enabledLabel.append(enabledText, enabled);
|
||||||
row.append(info, enabledLabel);
|
row.append(info, enabledLabel);
|
||||||
if (!server.builtin) {
|
if (!server.builtin) {
|
||||||
const remove = document.createElement('button');
|
const remove = document.createElement('button');
|
||||||
remove.className = 'discard';
|
remove.className = 'discard';
|
||||||
remove.textContent = 'Remove';
|
remove.textContent = 'Remove';
|
||||||
remove.onclick = async () => {
|
remove.onclick = async () => {
|
||||||
try {
|
try {
|
||||||
await window.daybreakMail.pgp.removeKeyServer(server.id);
|
await window.daybreakMail.pgp.removeKeyServer(server.id);
|
||||||
await renderKeyServers();
|
await renderKeyServers();
|
||||||
status('Custom key server removed.');
|
status('Custom key server removed.');
|
||||||
} catch (error) { status(error.message || 'Could not remove the key server.'); }
|
} catch (error) { status(error.message || 'Could not remove the key server.'); }
|
||||||
};
|
};
|
||||||
row.append(remove);
|
row.append(remove);
|
||||||
}
|
}
|
||||||
list.append(row);
|
list.append(row);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
selectPgpKeyUi('#pgp-find-key').onclick = async () => {
|
selectPgpKeyUi('#pgp-find-key').onclick = async () => {
|
||||||
const button = selectPgpKeyUi('#pgp-find-key');
|
const button = selectPgpKeyUi('#pgp-find-key');
|
||||||
const results = selectPgpKeyUi('#pgp-found-keys');
|
const results = selectPgpKeyUi('#pgp-found-keys');
|
||||||
button.disabled = true;
|
button.disabled = true;
|
||||||
results.textContent = 'Searching…';
|
results.textContent = 'Searching…';
|
||||||
try {
|
try {
|
||||||
const found = await window.daybreakMail.pgp.findKey({
|
const found = await window.daybreakMail.pgp.findKey({
|
||||||
email: selectPgpKeyUi('#pgp-search-email').value
|
email: selectPgpKeyUi('#pgp-search-email').value
|
||||||
});
|
});
|
||||||
results.replaceChildren();
|
results.replaceChildren();
|
||||||
found.keys.forEach(key => {
|
found.keys.forEach(key => {
|
||||||
const row = document.createElement('div');
|
const row = document.createElement('div');
|
||||||
row.className = 'attachment-row';
|
row.className = 'attachment-row';
|
||||||
const info = document.createElement('div');
|
const info = document.createElement('div');
|
||||||
info.className = 'attachment-row-info';
|
info.className = 'attachment-row-info';
|
||||||
const title = document.createElement('strong');
|
const title = document.createElement('strong');
|
||||||
title.textContent = key.emails.join(', ') || key.name || 'Public key';
|
title.textContent = key.emails.join(', ') || key.name || 'Public key';
|
||||||
const meta = document.createElement('small');
|
const meta = document.createElement('small');
|
||||||
meta.textContent = `Found on ${key.sources.join(', ')} · not verified`;
|
meta.textContent = `Found on ${key.sources.join(', ')} · not verified`;
|
||||||
const fingerprint = document.createElement('small');
|
const fingerprint = document.createElement('small');
|
||||||
fingerprint.textContent = `Fingerprint: ${key.fingerprint.match(/.{1,4}/g).join(' ')}`;
|
fingerprint.textContent = `Fingerprint: ${key.fingerprint.match(/.{1,4}/g).join(' ')}`;
|
||||||
info.append(title, meta, fingerprint);
|
info.append(title, meta, fingerprint);
|
||||||
const add = document.createElement('button');
|
const add = document.createElement('button');
|
||||||
add.className = 'discard';
|
add.className = 'discard';
|
||||||
add.textContent = 'Add to contacts…';
|
add.textContent = 'Add to contacts…';
|
||||||
add.onclick = async () => {
|
add.onclick = async () => {
|
||||||
add.disabled = true;
|
add.disabled = true;
|
||||||
try {
|
try {
|
||||||
const result = await window.daybreakMail.pgp.addContact({ armoredKey: key.armoredKey, source: 'keyserver' });
|
const result = await window.daybreakMail.pgp.addContact({ armoredKey: key.armoredKey, source: 'keyserver' });
|
||||||
if (result.canceled) return;
|
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.');
|
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();
|
await renderContacts();
|
||||||
row.remove();
|
row.remove();
|
||||||
} catch (error) { status(error.message || 'Could not add the public key.'); }
|
} catch (error) { status(error.message || 'Could not add the public key.'); }
|
||||||
finally { add.disabled = false; }
|
finally { add.disabled = false; }
|
||||||
};
|
};
|
||||||
row.append(info, add);
|
row.append(info, add);
|
||||||
results.append(row);
|
results.append(row);
|
||||||
});
|
});
|
||||||
found.errors.forEach(error => {
|
found.errors.forEach(error => {
|
||||||
const warning = document.createElement('small');
|
const warning = document.createElement('small');
|
||||||
warning.textContent = `${error.name}: ${error.message}`;
|
warning.textContent = `${error.name}: ${error.message}`;
|
||||||
results.append(warning);
|
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 && !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.` : ''}`);
|
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 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).`);
|
else status(`No matching key found across ${found.searchedServers.length} enabled server(s).`);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
results.textContent = '';
|
results.textContent = '';
|
||||||
status(error.message || 'Could not search the key server.');
|
status(error.message || 'Could not search the key server.');
|
||||||
} finally { button.disabled = false; }
|
} finally { button.disabled = false; }
|
||||||
};
|
};
|
||||||
selectPgpKeyUi('#pgp-add-server').onclick = async () => {
|
selectPgpKeyUi('#pgp-add-server').onclick = async () => {
|
||||||
const button = selectPgpKeyUi('#pgp-add-server');
|
const button = selectPgpKeyUi('#pgp-add-server');
|
||||||
button.disabled = true;
|
button.disabled = true;
|
||||||
try {
|
try {
|
||||||
const result = await window.daybreakMail.pgp.addKeyServer({
|
const result = await window.daybreakMail.pgp.addKeyServer({
|
||||||
name: selectPgpKeyUi('#pgp-server-name').value,
|
name: selectPgpKeyUi('#pgp-server-name').value,
|
||||||
url: selectPgpKeyUi('#pgp-server-url').value,
|
url: selectPgpKeyUi('#pgp-server-url').value,
|
||||||
protocol: selectPgpKeyUi('#pgp-server-protocol').value
|
protocol: selectPgpKeyUi('#pgp-server-protocol').value
|
||||||
});
|
});
|
||||||
if (result.canceled) return;
|
if (result.canceled) return;
|
||||||
selectPgpKeyUi('#pgp-server-name').value = '';
|
selectPgpKeyUi('#pgp-server-name').value = '';
|
||||||
selectPgpKeyUi('#pgp-server-url').value = '';
|
selectPgpKeyUi('#pgp-server-url').value = '';
|
||||||
await renderKeyServers();
|
await renderKeyServers();
|
||||||
status('Custom key server added.');
|
status('Custom key server added.');
|
||||||
} catch (error) { status(error.message || 'Could not add the key server.'); }
|
} catch (error) { status(error.message || 'Could not add the key server.'); }
|
||||||
finally { button.disabled = false; }
|
finally { button.disabled = false; }
|
||||||
};
|
};
|
||||||
window.daybreakMail.pgp.getSettings().then(settings => { selectPgpKeyUi('#pgp-cache-minutes').value = settings.cacheMinutes; }).catch(() => {});
|
window.daybreakMail.pgp.getSettings().then(settings => { selectPgpKeyUi('#pgp-cache-minutes').value = settings.cacheMinutes; }).catch(() => {});
|
||||||
selectPgpKeyUi('#pgp-save-cache').onclick = async () => {
|
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).`); }
|
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.'); }
|
||||||
};
|
};
|
||||||
selectPgpKeyUi('#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 renderKeyServers();
|
||||||
void renderContacts();
|
void renderContacts();
|
||||||
void render();
|
void render();
|
||||||
}
|
}
|
||||||
|
|
||||||
window.epMailFeatures.productivity.wrapOpenPreferences(baseOpenPreferences => function () {
|
window.epMailFeatures.productivity.wrapOpenPreferences(baseOpenPreferences => function () {
|
||||||
baseOpenPreferences();
|
baseOpenPreferences();
|
||||||
const fields = selectPgpKeyUi('#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';
|
||||||
button.className = 'discard';
|
button.className = 'discard';
|
||||||
button.id = 'open-encryption-keys';
|
button.id = 'open-encryption-keys';
|
||||||
button.textContent = 'Encryption keys…';
|
button.textContent = 'Encryption keys…';
|
||||||
button.onclick = openEncryptionKeys;
|
button.onclick = openEncryptionKeys;
|
||||||
fields.append(button);
|
fields.append(button);
|
||||||
});
|
});
|
||||||
})();
|
})();
|
||||||
|
|||||||
@@ -6,50 +6,50 @@ const selectAllProductivityUi = productivityMailUi.selectAll;
|
|||||||
const toastProductivityUi = productivityMailUi.toast;
|
const toastProductivityUi = productivityMailUi.toast;
|
||||||
const escapeProductivityUi = productivityMailUi.escapeHtml;
|
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));
|
||||||
let profileSettings = productRead(productKeys.profile, { name: '' });
|
let profileSettings = productRead(productKeys.profile, { name: '' });
|
||||||
if (/^mira(\s+sol)?$/i.test(profileSettings.name || '')) { profileSettings = { name: '' }; localStorage.removeItem(productKeys.profile); }
|
if (/^mira(\s+sol)?$/i.test(profileSettings.name || '')) { profileSettings = { name: '' }; localStorage.removeItem(productKeys.profile); }
|
||||||
let calendarMonth = new Date(new Date().getFullYear(), new Date().getMonth(), 1);
|
let calendarMonth = new Date(new Date().getFullYear(), new Date().getMonth(), 1);
|
||||||
const generatedContactEmails = new Set(['amelia@northstar.design','jonah@fieldnotes.co','sofia@smallhours.works','mateo@roam.travel','eden@paperandpine.com','noah@common-thread.org','iris@littlefern.press']);
|
const generatedContactEmails = new Set(['amelia@northstar.design','jonah@fieldnotes.co','sofia@smallhours.works','mateo@roam.travel','eden@paperandpine.com','noah@common-thread.org','iris@littlefern.press']);
|
||||||
let savedContacts = productRead(productKeys.contacts, []).filter(contact => !generatedContactEmails.has(String(contact.email||'').toLowerCase()));
|
let savedContacts = productRead(productKeys.contacts, []).filter(contact => !generatedContactEmails.has(String(contact.email||'').toLowerCase()));
|
||||||
productWrite(productKeys.contacts, savedContacts);
|
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=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 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=selectProductivityUi('#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="${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>`;
|
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='';
|
||||||
selectAllProductivityUi('.modal-close').forEach(button=>button.onclick=close);
|
selectAllProductivityUi('.modal-close').forEach(button=>button.onclick=close);
|
||||||
selectProductivityUi('.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()};
|
||||||
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')};
|
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')};
|
||||||
selectProductivityUi('#profile-name').focus();
|
selectProductivityUi('#profile-name').focus();
|
||||||
}
|
}
|
||||||
function openPreferences() {
|
function openPreferences() {
|
||||||
const root=selectProductivityUi('#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='';
|
||||||
selectAllProductivityUi('.modal-close').forEach(button=>button.onclick=close);
|
selectAllProductivityUi('.modal-close').forEach(button=>button.onclick=close);
|
||||||
selectProductivityUi('.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()};
|
||||||
selectProductivityUi('#save-appearance').onclick=()=>{productivityMailUi.applyTheme(selectProductivityUi('#theme-select').value);close();toastProductivityUi('Appearance saved')};
|
selectProductivityUi('#save-appearance').onclick=()=>{productivityMailUi.applyTheme(selectProductivityUi('#theme-select').value);close();toastProductivityUi('Appearance saved')};
|
||||||
selectProductivityUi('#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=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 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}">${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 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=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 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:${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 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((productivityMailUi.connectedAccount?.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=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 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())){toastProductivityUi('That label already exists');return}customLabels.push(clean);productWrite(productKeys.labels,customLabels);renderLabels();toastProductivityUi('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(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()}
|
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=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')}}
|
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();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 ↓';});
|
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);toastProductivityUi(`Labeled ${label}`);productivityMailUi.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()}
|
||||||
productivityMailUi.wrapRenderList(baseMessageRenderer => function () {
|
productivityMailUi.wrapRenderList(baseMessageRenderer => function () {
|
||||||
const state = productivityMailUi.state;
|
const state = productivityMailUi.state;
|
||||||
if (state.activeFolder === 'Drafts') {
|
if (state.activeFolder === 'Drafts') {
|
||||||
@@ -71,7 +71,7 @@ productivityMailUi.wrapRenderList(baseMessageRenderer => function () {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
return baseMessageRenderer();
|
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);
|
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({
|
window.epMailFeatures.productivity = Object.freeze({
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
const CACHE='ep-mail-v12';
|
const CACHE='ep-mail-v12';
|
||||||
const FILES=['./','./index.html','./styles.css','./branding.css','./renderer-state.js','./mail-content-security.js','./renderer-mail-api.js','./app.js','./platform-bridge-loader.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-loader.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'))))});
|
||||||
|
|||||||
@@ -6,102 +6,102 @@ const selectShortcutUi = shortcutMailUi.select;
|
|||||||
const toastShortcutUi = shortcutMailUi.toast;
|
const toastShortcutUi = shortcutMailUi.toast;
|
||||||
const escapeShortcutUi = shortcutMailUi.escapeHtml;
|
const escapeShortcutUi = shortcutMailUi.escapeHtml;
|
||||||
const shortcutStorageKey = 'daybreak-shortcuts';
|
const shortcutStorageKey = 'daybreak-shortcuts';
|
||||||
const shortcutActions = [
|
const shortcutActions = [
|
||||||
{ id: 'compose', label: 'Compose', fallback: 'c', run: () => selectShortcutUi('#compose')?.click() },
|
{ id: 'compose', label: 'Compose', fallback: 'c', run: () => selectShortcutUi('#compose')?.click() },
|
||||||
{ id: 'search', label: 'Search', fallback: '/', run: () => selectShortcutUi('#search')?.focus() },
|
{ id: 'search', label: 'Search', fallback: '/', run: () => selectShortcutUi('#search')?.focus() },
|
||||||
{ id: 'refresh', label: 'Refresh', fallback: 'r', run: () => selectShortcutUi('#refresh')?.click() },
|
{ id: 'refresh', label: 'Refresh', fallback: 'r', run: () => selectShortcutUi('#refresh')?.click() },
|
||||||
{ id: 'archive', label: 'Archive message', fallback: 'e', run: () => selectShortcutUi('#reader-archive')?.click() },
|
{ id: 'archive', label: 'Archive message', fallback: 'e', run: () => selectShortcutUi('#reader-archive')?.click() },
|
||||||
{ id: 'delete', label: 'Delete message', fallback: '#', run: () => selectShortcutUi('#reader-delete')?.click() },
|
{ id: 'delete', label: 'Delete message', fallback: '#', run: () => selectShortcutUi('#reader-delete')?.click() },
|
||||||
{ id: 'star', label: 'Star message', fallback: 's', run: () => selectShortcutUi('#reader-star')?.click() },
|
{ id: 'star', label: 'Star message', fallback: 's', run: () => selectShortcutUi('#reader-star')?.click() },
|
||||||
{ id: 'reply', label: 'Reply', fallback: 'a', run: () => selectShortcutUi('#reply')?.click() },
|
{ id: 'reply', label: 'Reply', fallback: 'a', run: () => selectShortcutUi('#reply')?.click() },
|
||||||
{ id: 'forward', label: 'Forward', fallback: 'f', run: () => selectShortcutUi('#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) }
|
||||||
];
|
];
|
||||||
|
|
||||||
function normalizeShortcut(value) {
|
function normalizeShortcut(value) {
|
||||||
const text = String(value || '').trim();
|
const text = String(value || '').trim();
|
||||||
if (!text) return '';
|
if (!text) return '';
|
||||||
const parts = text.split('+').map(part => part.trim()).filter(Boolean);
|
const parts = text.split('+').map(part => part.trim()).filter(Boolean);
|
||||||
const key = parts.pop() || '+';
|
const key = parts.pop() || '+';
|
||||||
const mods = ['Ctrl', 'Alt', 'Shift'].filter(mod => parts.some(part => part.toLowerCase() === mod.toLowerCase()));
|
const mods = ['Ctrl', 'Alt', 'Shift'].filter(mod => parts.some(part => part.toLowerCase() === mod.toLowerCase()));
|
||||||
return [...mods, key.length === 1 ? key.toLowerCase() : key].join('+');
|
return [...mods, key.length === 1 ? key.toLowerCase() : key].join('+');
|
||||||
}
|
}
|
||||||
|
|
||||||
function loadShortcuts() {
|
function loadShortcuts() {
|
||||||
let saved = {};
|
let saved = {};
|
||||||
try { saved = JSON.parse(localStorage.getItem(shortcutStorageKey)) || {}; } catch {}
|
try { saved = JSON.parse(localStorage.getItem(shortcutStorageKey)) || {}; } catch {}
|
||||||
return Object.fromEntries(shortcutActions.map(action => [
|
return Object.fromEntries(shortcutActions.map(action => [
|
||||||
action.id, typeof saved[action.id] === 'string' ? normalizeShortcut(saved[action.id]) : action.fallback
|
action.id, typeof saved[action.id] === 'string' ? normalizeShortcut(saved[action.id]) : action.fallback
|
||||||
]));
|
]));
|
||||||
}
|
}
|
||||||
|
|
||||||
function eventShortcut(event) {
|
function eventShortcut(event) {
|
||||||
if (['Control', 'Alt', 'Shift', 'Meta'].includes(event.key)) return '';
|
if (['Control', 'Alt', 'Shift', 'Meta'].includes(event.key)) return '';
|
||||||
const mods = [event.ctrlKey || event.metaKey ? 'Ctrl' : '', event.altKey ? 'Alt' : ''];
|
const mods = [event.ctrlKey || event.metaKey ? 'Ctrl' : '', event.altKey ? 'Alt' : ''];
|
||||||
const printable = event.key.length === 1;
|
const printable = event.key.length === 1;
|
||||||
if (event.shiftKey && !printable) mods.push('Shift');
|
if (event.shiftKey && !printable) mods.push('Shift');
|
||||||
return normalizeShortcut([...mods.filter(Boolean), event.key === ' ' ? 'Space' : event.key].join('+'));
|
return normalizeShortcut([...mods.filter(Boolean), event.key === ' ' ? 'Space' : event.key].join('+'));
|
||||||
}
|
}
|
||||||
|
|
||||||
function moveMessageSelection(step) {
|
function moveMessageSelection(step) {
|
||||||
const messages = shortcutMailUi.state.messages;
|
const messages = shortcutMailUi.state.messages;
|
||||||
if (!messages.length) return;
|
if (!messages.length) return;
|
||||||
const index = messages.findIndex(message => message.id === shortcutMailUi.state.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) { shortcutMailUi.openMessage(next.id); selectShortcutUi(`.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"]') || selectShortcutUi('#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();
|
||||||
const action = shortcutActions.find(item => shortcuts[item.id] && shortcuts[item.id] === pressed);
|
const action = shortcutActions.find(item => shortcuts[item.id] && shortcuts[item.id] === pressed);
|
||||||
if (!action) return;
|
if (!action) return;
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
action.run();
|
action.run();
|
||||||
});
|
});
|
||||||
|
|
||||||
shortcutProductivityUi.wrapOpenPreferences(baseOpenPreferences => function () {
|
shortcutProductivityUi.wrapOpenPreferences(baseOpenPreferences => function () {
|
||||||
baseOpenPreferences();
|
baseOpenPreferences();
|
||||||
const fields = selectShortcutUi('#modal-root .compose-fields');
|
const fields = selectShortcutUi('#modal-root .compose-fields');
|
||||||
const save = selectShortcutUi('#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="${escapeShortcutUi(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');
|
||||||
if (!input || ['Tab', 'Escape'].includes(event.key)) return;
|
if (!input || ['Tab', 'Escape'].includes(event.key)) return;
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
if (['Backspace', 'Delete'].includes(event.key)) { input.value = ''; return; }
|
if (['Backspace', 'Delete'].includes(event.key)) { input.value = ''; return; }
|
||||||
const combo = eventShortcut(event);
|
const combo = eventShortcut(event);
|
||||||
if (combo) input.value = combo;
|
if (combo) input.value = combo;
|
||||||
});
|
});
|
||||||
selectShortcutUi('#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;
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
const baseSave = save.onclick;
|
const baseSave = save.onclick;
|
||||||
save.onclick = event => {
|
save.onclick = event => {
|
||||||
const values = {};
|
const values = {};
|
||||||
const used = new Map();
|
const used = new Map();
|
||||||
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)) { toastShortcutUi(`“${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);
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
})();
|
})();
|
||||||
|
|||||||
@@ -3,91 +3,91 @@ const snoozeMailUi = window.epMailFeatures.mail;
|
|||||||
const snoozeProductivityUi = window.epMailFeatures.productivity;
|
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);
|
||||||
}
|
}
|
||||||
|
|
||||||
function nextMorning(daysAhead) {
|
function nextMorning(daysAhead) {
|
||||||
const date = new Date();
|
const date = new Date();
|
||||||
date.setDate(date.getDate() + daysAhead);
|
date.setDate(date.getDate() + daysAhead);
|
||||||
date.setHours(9, 0, 0, 0);
|
date.setHours(9, 0, 0, 0);
|
||||||
if (date <= new Date()) date.setDate(date.getDate() + 1);
|
if (date <= new Date()) date.setDate(date.getDate() + 1);
|
||||||
return date;
|
return date;
|
||||||
}
|
}
|
||||||
|
|
||||||
function openSnoozeDialog(items) {
|
function openSnoozeDialog(items) {
|
||||||
const eligible = items.filter(message => message?.uid && snoozeMailUi.connectedAccount);
|
const eligible = items.filter(message => message?.uid && snoozeMailUi.connectedAccount);
|
||||||
if (!eligible.length) {
|
if (!eligible.length) {
|
||||||
snoozeMailUi.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 = snoozeMailUi.select('#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>`;
|
||||||
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 => {
|
root.querySelector('.modal-overlay').onclick = event => {
|
||||||
if (event.target.classList.contains('modal-overlay')) close();
|
if (event.target.classList.contains('modal-overlay')) close();
|
||||||
};
|
};
|
||||||
|
|
||||||
const schedule = async dueAt => {
|
const schedule = async dueAt => {
|
||||||
if (!Number.isFinite(dueAt) || dueAt <= Date.now()) {
|
if (!Number.isFinite(dueAt) || dueAt <= Date.now()) {
|
||||||
snoozeMailUi.select('#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')];
|
||||||
buttons.forEach(button => { button.disabled = true; });
|
buttons.forEach(button => { button.disabled = true; });
|
||||||
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(snoozeMailUi.state.activeFolder) ? snoozeMailUi.state.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,
|
||||||
sourceFolder,
|
sourceFolder,
|
||||||
dueAt,
|
dueAt,
|
||||||
subject: message.subject
|
subject: message.subject
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
close();
|
close();
|
||||||
snoozeMailUi.toast(eligible.length === 1 ? 'Message snoozed' : `${eligible.length} messages snoozed`);
|
snoozeMailUi.toast(eligible.length === 1 ? 'Message snoozed' : `${eligible.length} messages snoozed`);
|
||||||
snoozeMailUi.state.selectedIds.clear();
|
snoozeMailUi.state.selectedIds.clear();
|
||||||
await snoozeMailUi.syncMailbox(false, { offset: 0 });
|
await snoozeMailUi.syncMailbox(false, { offset: 0 });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
snoozeMailUi.select('#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; });
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
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));
|
||||||
});
|
});
|
||||||
snoozeMailUi.select('#snooze-custom').onclick = () => schedule(new Date(snoozeMailUi.select('#snooze-custom-time').value).getTime());
|
snoozeMailUi.select('#snooze-custom').onclick = () => schedule(new Date(snoozeMailUi.select('#snooze-custom-time').value).getTime());
|
||||||
snoozeMailUi.select('#snooze-custom-time').focus();
|
snoozeMailUi.select('#snooze-custom-time').focus();
|
||||||
}
|
}
|
||||||
|
|
||||||
function unsnoozeMessage(message) {
|
function unsnoozeMessage(message) {
|
||||||
const sourceFolder = message.sourceFolder || 'Inbox';
|
const sourceFolder = message.sourceFolder || 'Inbox';
|
||||||
window.daybreakMail.setSnooze({
|
window.daybreakMail.setSnooze({
|
||||||
uid: message.uid,
|
uid: message.uid,
|
||||||
sourceFolder,
|
sourceFolder,
|
||||||
dueAt: null
|
dueAt: null
|
||||||
}).then(async () => {
|
}).then(async () => {
|
||||||
snoozeMailUi.toast('Message returned to its mailbox');
|
snoozeMailUi.toast('Message returned to its mailbox');
|
||||||
await snoozeMailUi.syncMailbox(false, { offset: 0 });
|
await snoozeMailUi.syncMailbox(false, { offset: 0 });
|
||||||
}).catch(error => snoozeMailUi.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 = snoozeMailUi.select('#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 => {
|
||||||
if (event.target.classList.contains('modal-overlay')) root.innerHTML = '';
|
if (event.target.classList.contains('modal-overlay')) root.innerHTML = '';
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
snoozeMailUi.wrapRenderList(renderListBeforeSnooze => function () {
|
snoozeMailUi.wrapRenderList(renderListBeforeSnooze => function () {
|
||||||
if (snoozeMailUi.state.activeFolder === 'Snoozed') {
|
if (snoozeMailUi.state.activeFolder === 'Snoozed') {
|
||||||
const originalMessages = snoozeMailUi.state.messages.slice();
|
const originalMessages = snoozeMailUi.state.messages.slice();
|
||||||
@@ -99,21 +99,21 @@ snoozeMailUi.wrapRenderList(renderListBeforeSnooze => function () {
|
|||||||
snoozeMailUi.state.activeFolder = 'Inbox';
|
snoozeMailUi.state.activeFolder = 'Inbox';
|
||||||
snoozeMailUi.baseRenderList();
|
snoozeMailUi.baseRenderList();
|
||||||
snoozeMailUi.state.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;
|
||||||
});
|
});
|
||||||
snoozeMailUi.state.messages.splice(0, snoozeMailUi.state.messages.length, ...originalMessages);
|
snoozeMailUi.state.messages.splice(0, snoozeMailUi.state.messages.length, ...originalMessages);
|
||||||
for (const row of snoozeMailUi.selectAll('.message')) {
|
for (const row of snoozeMailUi.selectAll('.message')) {
|
||||||
const message = snoozeMailUi.state.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()}`;
|
||||||
const snippet = row.querySelector('.snippet');
|
const snippet = row.querySelector('.snippet');
|
||||||
if (snippet) snippet.textContent = `Reminder · ${due.toLocaleString()} · ${message.snippet}`;
|
if (snippet) snippet.textContent = `Reminder · ${due.toLocaleString()} · ${message.snippet}`;
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
return renderListBeforeSnooze();
|
return renderListBeforeSnooze();
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -121,61 +121,61 @@ snoozeMailUi.wrapOpenMessage(openMessageBeforeSnooze => function (id) {
|
|||||||
openMessageBeforeSnooze(id);
|
openMessageBeforeSnooze(id);
|
||||||
const message = snoozeMailUi.state.messages.find(item => item.id === id);
|
const message = snoozeMailUi.state.messages.find(item => item.id === id);
|
||||||
const tools = snoozeMailUi.select('.reader-tools');
|
const tools = snoozeMailUi.select('.reader-tools');
|
||||||
if (!message || !tools) return;
|
if (!message || !tools) return;
|
||||||
const snoozed = snoozeMailUi.state.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', () => {
|
||||||
snoozeMailUi.select('#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));
|
||||||
void checkReminders();
|
void checkReminders();
|
||||||
setInterval(checkReminders, 60 * 1000);
|
setInterval(checkReminders, 60 * 1000);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
document.addEventListener('click', event => {
|
document.addEventListener('click', event => {
|
||||||
const action = event.target.closest('[data-message-action]');
|
const action = event.target.closest('[data-message-action]');
|
||||||
const more = event.target.closest('.reader-tools button[title="More"]');
|
const more = event.target.closest('.reader-tools button[title="More"]');
|
||||||
const snooze = event.target.closest('#reader-snooze, #snooze-selected');
|
const snooze = event.target.closest('#reader-snooze, #snooze-selected');
|
||||||
const unsnooze = event.target.closest('#reader-unsnooze');
|
const unsnooze = event.target.closest('#reader-unsnooze');
|
||||||
if (!more && !snooze && !unsnooze && !action) return;
|
if (!more && !snooze && !unsnooze && !action) return;
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
event.stopImmediatePropagation();
|
event.stopImmediatePropagation();
|
||||||
if (action) {
|
if (action) {
|
||||||
const message = snoozeMailUi.state.messages.find(item => item.id === snoozeMailUi.state.activeMessage);
|
const message = snoozeMailUi.state.messages.find(item => item.id === snoozeMailUi.state.activeMessage);
|
||||||
snoozeMailUi.select('#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') snoozeProductivityUi.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;
|
||||||
snoozeMailUi.renderList();
|
snoozeMailUi.renderList();
|
||||||
snoozeMailUi.toast(type === 'unread' ? 'Marked unread' : 'Moved to Inbox');
|
snoozeMailUi.toast(type === 'unread' ? 'Marked unread' : 'Moved to Inbox');
|
||||||
}).catch(error => snoozeMailUi.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 = snoozeMailUi.state.messages.find(item => item.id === snoozeMailUi.state.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(snoozeMailUi.state.messages.filter(message => snoozeMailUi.state.selectedIds.has(message.id)));
|
openSnoozeDialog(snoozeMailUi.state.messages.filter(message => snoozeMailUi.state.selectedIds.has(message.id)));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (more) {
|
if (more) {
|
||||||
const message = snoozeMailUi.state.messages.find(item => item.id === snoozeMailUi.state.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 = snoozeMailUi.state.messages.find(item => item.id === snoozeMailUi.state.activeMessage);
|
const message = snoozeMailUi.state.messages.find(item => item.id === snoozeMailUi.state.activeMessage);
|
||||||
if (message) openSnoozeDialog([message]);
|
if (message) openSnoozeDialog([message]);
|
||||||
}, true);
|
}, true);
|
||||||
})();
|
})();
|
||||||
|
|||||||