Compare commits

..
4 Commits
Author SHA1 Message Date
thuttuandCopilot bae9c7966d Add OpenPGP key management foundation (encryption phase 1) and encryption plan, v0.2.4
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-07 13:06:51 +03:00
thuttuandCopilot b9e2f7fa30 Bump version to 0.2.3
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-07 10:16:22 +03:00
thuttuandCopilot 5529a8f18f Add attachment previews and attachments view
Bump version to 0.2.2

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-07 10:15:10 +03:00
thuttuandCopilot 63ee146719 Add configurable keyboard shortcuts
Bump version to 0.2.1

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-07 10:06:19 +03:00
27 changed files with 1274 additions and 11 deletions
+75
View File
@@ -0,0 +1,75 @@
# Encryption plan: OpenPGP mail encryption for ep-mail
Status: **Phase 1 (foundation) is implemented on desktop.** Phases 2–6 are tracked in [TODO.md](./TODO.md).
## 1. Format: OpenPGP with PGP/MIME (RFC 3156)
| Option | Pros | Cons |
|---|---|---|
| **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. |
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.
- Messages: `multipart/encrypted` (`application/pgp-encrypted` + `application/octet-stream`), signed and encrypted together. Attachments go inside the encrypted payload.
- Keys: Curve25519 with modern defaults.
- Also detect and decrypt legacy inline PGP (`-----BEGIN PGP MESSAGE-----`).
- Out of scope for v1: Autocrypt headers, key servers, Web Key Directory.
## 2. Key handling
**Private keys**
- 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).
- 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.
- 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.
**Public keys**
- Per-account contact keyring: address, fingerprint, trust level, source.
- Sources: file import, attached to received mail, 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.
## 3. User experience
- 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.
- Message list: lock icon for encrypted mail.
- 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.
## 4. Threat model and limits
- Protects content from the mail server and network observers.
- Does not protect metadata (sender, recipients, subject, timestamps).
- 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.
## 5. Phases
| 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) |
| 2 | Receive: detect PGP/MIME and inline PGP, decrypt on open, verify signatures, status UI, missing-key and wrong-passphrase handling | Planned |
| 3 | Send: public-key keyring and contact import, encrypt and sign on compose, encrypted Sent copy, downgrade warnings | Planned |
| 4 | Trust and polish: fingerprint verification, key-change warnings, passphrase cache timeout, Android Keystore and biometric unlock | Planned |
| 5 | Interop testing with Thunderbird and GnuPG, large attachments, multiple recipients, corrupted payloads | Planned |
| 6 | Docs, security review, release | Planned |
## 6. Phase 1 implementation notes
- [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/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).
- Tests: `npm test` ([tests/pgp-keystore.test.cjs](./tests/pgp-keystore.test.cjs)).
## 7. Risks
- Android WebView performance with large attachments (may need native handling).
- Key loss (backup flow, revocation certificate).
- 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.
- Security-critical code: have it reviewed by someone with cryptography experience before relying on it.
+1 -1
View File
@@ -31,4 +31,4 @@ On Windows, `py -m http.server 8000` is also available on many Python installati
## Current scope
Mail supports multiple IMAP/SMTP accounts, switching between them, and saving message attachments. CalDAV and CardDAV servers can be added from the Calendar and Contacts views; credentials are kept in the OS-encrypted credential store, and events and contacts can sync and be edited on the server. Local contacts and events remain available without a DAV connection. Your display name is saved locally and appears in the greeting. Use the **+** beside **Folders** in the sidebar to create IMAP folders on the server; your custom folders appear in the sidebar and can be opened like any other folder.
Mail supports multiple IMAP/SMTP accounts, switching between them, and saving message attachments. CalDAV and CardDAV servers can be added from the Calendar and Contacts views; credentials are kept in the OS-encrypted credential store, and events and contacts can sync and be edited on the server. Local contacts and events remain available without a DAV connection. Your display name is saved locally and appears in the greeting. Use the **+** beside **Folders** in the sidebar to create IMAP folders on the server; your custom folders appear in the sidebar and can be opened like any other folder. Keyboard shortcuts for compose, search, refresh, archive, delete, star, reply, forward, and message navigation can be changed in **Settings**. Attachments can be previewed (images and text) in the reader, and the **Attachments** view in the sidebar lists, searches, filters by type, previews and downloads attachments across Inbox, Sent, Archive and Trash. On desktop, **Settings → Encryption keys** creates, imports and exports passphrase-protected OpenPGP keys, stored encrypted by the operating system; sending and reading encrypted mail is planned (see [ENCRYPTION_PLAN.md](./ENCRYPTION_PLAN.md)). Run the tests with `npm test`.
+9 -3
View File
@@ -15,8 +15,8 @@
- [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.
- [ ] Group related messages into conversations, with controls to expand or collapse threads.
- [ ] Add attachment previews and a dedicated view to find and manage attachments across mailboxes.
- [ ] Add configurable keyboard shortcuts for common actions such as compose, archive, reply, and search.
- [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] 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 signatures, notification preferences, and sync settings.
@@ -25,7 +25,13 @@
## Mail security
- [ ] Add support for encrypting and decrypting mail with private/public keys or a suitable standard. Decide on the encryption format, key storage and exchange flow, and compatibility requirements before implementation.
- [ ] Add support for encrypting and decrypting mail with OpenPGP (PGP/MIME). 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.
- [ ] 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.
- [ ] 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.
- [ ] Phase 4: trust and polish — fingerprint verification, key-change warnings, passphrase cache timeout, Android Keystore key storage and biometric unlock (key management is desktop-only until then).
- [ ] Phase 5: interoperability testing with Thunderbird and GnuPG, large attachments, multiple recipients, corrupted payloads.
- [ ] Phase 6: documentation, security review, release.
## Appearance and settings
@@ -345,6 +345,40 @@ internal object AndroidMailService {
}
}
fun previewAttachment(account: JSONObject, input: JSONObject): JSONObject =
withStore(account) { _, store ->
val folder = resolveFolder(store, input.optString("folder", "Inbox"))
?: throw IllegalStateException("That mail folder could not be found.")
folder.open(Folder.READ_ONLY)
try {
val message = (folder as? UIDFolder)?.getMessageByUID(input.optLong("uid"))
?: throw IllegalStateException("The message is no longer available.")
val filename = input.optString("filename")
val part = findAttachment(message, filename)
?: throw IllegalStateException("No attachment was found in this message.")
val mimeType = part.contentType.substringBefore(';').trim().lowercase(Locale.ROOT)
val none = JSONObject().put("kind", "none")
.put("reason", "No preview is available for this file type. Download it to open it.")
if (Regex("image/(png|jpe?g|gif|webp|bmp|svg\\+xml)").matches(mimeType)) {
val bytes = part.inputStream.use { it.readBytes() }
if (bytes.size > 5 * 1048576) {
none.put("reason", "This image is too large to preview. Download it instead.")
} else {
JSONObject().put("kind", "image").put(
"dataUrl", "data:$mimeType;base64," + android.util.Base64.encodeToString(bytes, android.util.Base64.NO_WRAP)
)
}
} else if (mimeType.startsWith("text/") || mimeType == "application/json" || mimeType == "application/xml") {
val bytes = part.inputStream.use { it.readBytes() }
JSONObject().put("kind", "text")
.put("text", String(bytes.copyOf(minOf(bytes.size, 100000)), Charsets.UTF_8))
.put("truncated", bytes.size > 100000)
} else none
} finally {
folder.close(false)
}
}
fun checkForNewMail(account: JSONObject): Int {
flushOutbox(account)
return withStore(account) { _, store ->
@@ -248,6 +248,17 @@ class EpMailPlugin : Plugin() {
}
}
@PluginMethod
fun previewAttachment(call: PluginCall) {
try {
val account = AndroidAccountVault.account()
?: throw IllegalStateException("Add a mail account before previewing attachments.")
call.resolve(AndroidMailService.previewAttachment(account, JSONObject(call.data.toString())).toJSObject())
} catch (error: Exception) {
call.reject(error.message ?: "Could not preview the attachment.")
}
}
@PluginMethod
fun openExternal(call: PluginCall) {
val raw = call.getString("url").orEmpty()
+161
View File
@@ -0,0 +1,161 @@
// Attachment previews and a dedicated view for finding and managing attachments across mailboxes.
const attachmentFolders = ['Inbox', 'Sent', 'Archive', 'Trash'];
let attachmentItems = [];
function attachmentKind(filename) {
const ext = String(filename).toLowerCase().split('.').pop();
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 (['zip', 'rar', '7z', 'tar', 'gz'].includes(ext)) return 'Archives';
return 'Other';
}
function attachmentSize(size) {
if (!size) return '';
if (typeof size === 'string') return size;
return size < 1048576 ? `${Math.max(1, Math.round(size / 1024))} KB` : `${(size / 1048576).toFixed(1)} MB`;
}
async function previewAttachment(target, details) {
if (!details.uid || !window.daybreakMail?.previewAttachment) {
target.textContent = 'Previews are available for connected mailbox messages.';
return;
}
target.textContent = 'Loading preview…';
try {
const result = await window.daybreakMail.previewAttachment(details);
target.replaceChildren();
if (result.kind === 'image') {
const image = document.createElement('img');
image.className = 'attachment-preview-image';
image.alt = details.filename;
image.src = result.dataUrl;
target.append(image);
} else if (result.kind === 'text') {
const pre = document.createElement('pre');
pre.className = 'attachment-preview-text';
pre.textContent = result.text + (result.truncated ? '\n… (preview truncated)' : '');
target.append(pre);
} else {
target.textContent = result.reason || 'No preview is available for this file type.';
}
} catch (error) {
target.textContent = error.message || 'Could not load the preview.';
}
}
function downloadAttachment(details) {
if (!details.uid || !window.daybreakMail?.saveAttachment) { toast('Attachment download is available for connected mailbox messages'); return; }
window.daybreakMail.saveAttachment(details)
.then(result => { if (result.saved) toast('Attachment saved'); })
.catch(error => toast(error.message || 'Could not save attachment'));
}
// Add a Preview button to each attachment in the reader.
if (typeof openMessage === 'function') {
const baseOpenMessage = openMessage;
openMessage = function (id) {
baseOpenMessage(id);
const message = messages.find(item => item.id === id);
if (!message?.uid) return;
$$('#reader-pane .attachment').forEach(row => {
const download = row.querySelector('.download');
if (!download || row.querySelector('.preview-attachment')) return;
const button = document.createElement('button');
button.className = 'preview-attachment icon-button';
button.title = 'Preview';
button.setAttribute('aria-label', `Preview ${download.dataset.filename}`);
button.textContent = '👁';
button.addEventListener('click', event => {
event.stopPropagation();
let panel = row.nextElementSibling?.classList.contains('attachment-preview') ? row.nextElementSibling : null;
if (panel) { panel.remove(); return; }
panel = document.createElement('div');
panel.className = 'attachment-preview';
row.after(panel);
void previewAttachment(panel, { uid: message.uid, folder: message.sourceFolder || activeFolder, filename: download.dataset.filename });
});
download.before(button);
});
};
}
async function collectAttachments() {
const items = [];
for (const folder of attachmentFolders) {
let offset = 0;
for (let page = 0; page < 5; page += 1) {
const result = await window.daybreakMail.syncFolder(folder, offset, { hasAttachments: true });
for (const message of result.messages || []) {
for (const file of message.attachments || []) {
items.push({
uid: message.uid, folder, filename: file.filename, size: file.size,
subject: message.subject, sender: message.sender, date: message.date, timestamp: Number(message.timestamp || 0),
kind: attachmentKind(file.filename)
});
}
}
offset += (result.messages || []).length;
if (!result.messages?.length || offset >= (result.total || 0)) break;
}
}
return items.sort((a, b) => b.timestamp - a.timestamp);
}
async function openAttachmentsView() {
if (!connectedMailAccount || !window.daybreakMail) { openMailAccount(); return; }
const root = $('#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>`;
const close = () => { root.innerHTML = ''; };
root.querySelector('.modal-close').onclick = close;
root.querySelector('.modal-overlay').onclick = event => { if (event.target.classList.contains('modal-overlay')) close(); };
const list = $('#attachment-list');
const render = () => {
const text = $('#attachment-search').value.trim().toLowerCase();
const type = $('#attachment-type').value;
const shown = attachmentItems.filter(item => (!type || item.kind === type) &&
(!text || `${item.filename} ${item.subject} ${item.sender}`.toLowerCase().includes(text)));
list.replaceChildren();
if (!shown.length) { list.textContent = attachmentItems.length ? 'No attachments match.' : 'No attachments found.'; return; }
shown.forEach(item => {
const row = document.createElement('div');
row.className = 'attachment-row';
const info = document.createElement('div');
info.className = 'attachment-row-info';
const name = document.createElement('strong');
name.textContent = item.filename;
const meta = document.createElement('small');
meta.textContent = [attachmentSize(item.size), item.sender, item.subject, item.folder, item.date].filter(Boolean).join(' · ');
info.append(name, meta);
const preview = document.createElement('button');
preview.className = 'discard';
preview.textContent = 'Preview';
const save = document.createElement('button');
save.className = 'discard';
save.textContent = 'Download';
const panel = document.createElement('div');
panel.className = 'attachment-preview';
panel.hidden = true;
const details = { uid: item.uid, folder: item.folder, filename: item.filename };
preview.onclick = () => {
panel.hidden = !panel.hidden;
if (!panel.hidden && !panel.childElementCount && !panel.textContent) void previewAttachment(panel, details);
};
save.onclick = () => downloadAttachment(details);
row.append(info, preview, save, panel);
list.append(row);
});
};
$('#attachment-search').oninput = render;
$('#attachment-type').onchange = render;
try {
attachmentItems = await collectAttachments();
if ($('#attachment-list')) render();
} catch (error) {
if ($('#attachment-list')) $('#attachment-list').textContent = error.message || 'Could not load attachments.';
}
}
document.addEventListener('DOMContentLoaded', () => {
$('#attachments-nav')?.addEventListener('click', openAttachmentsView);
});
+101
View File
@@ -193,6 +193,27 @@ async function reconcileIdleWatchers() {
for (const account of desiredAccounts) startIdleWatcher(account);
}
const { createKeyStore } = require('./pgp-keystore.cjs');
const pgpKeysPath = () => path.join(app.getPath('userData'), 'pgp-keys.enc');
const pgpKeys = createKeyStore({
async load() {
try {
const { result } = await safeStorage.decryptStringAsync(await fs.readFile(pgpKeysPath()));
return JSON.parse(result);
} catch (error) {
if (error.code === 'ENOENT') return { keys: [] };
throw error;
}
},
async save(data) {
if (!await safeStorage.isAsyncEncryptionAvailable()) throw new Error('Secure key storage is unavailable.');
await fs.mkdir(path.dirname(pgpKeysPath()), { recursive: true });
await fs.writeFile(`${pgpKeysPath()}.tmp`, await safeStorage.encryptStringAsync(JSON.stringify(data)), { mode: 0o600 });
await fs.rename(`${pgpKeysPath()}.tmp`, pgpKeysPath());
}
});
async function readDavStore() {
try {
const encrypted = await fs.readFile(davCredentialsPath());
@@ -1169,6 +1190,86 @@ ipcMain.handle('mail:save-attachment', async (event, input) => {
}
});
ipcMain.handle('mail:preview-attachment', async (_event, input) => {
const account = await readAccount();
if (!account) throw new Error('Add a mail account before previewing attachments.');
const uid = Number(input?.uid);
const folder = String(input?.folder || 'Inbox');
const filename = String(input?.filename || 'attachment');
if (!Number.isInteger(uid) || uid < 1) throw new Error('That message could not be identified.');
const client = imapClient(account);
try {
await client.connect();
const mailboxPath = await folderPath(client, folder);
if (!mailboxPath) throw new Error('That mail folder could not be found.');
const lock = await client.getMailboxLock(mailboxPath);
try {
const item = await client.fetchOne(uid, { uid: true, source: true }, { uid: true });
if (!item?.source) throw new Error('The message is no longer available.');
const parsed = await simpleParser(item.source);
const attachment = parsed.attachments?.find(file => (file.filename || 'attachment') === filename);
if (!attachment) throw new Error('No attachment was found in this message.');
const mimeType = String(attachment.contentType || '').toLowerCase().split(';')[0];
const size = attachment.content.length;
if (/^image\/(png|jpe?g|gif|webp|bmp|svg\+xml)$/.test(mimeType)) {
if (size > 5 * 1048576) return { kind: 'none', reason: 'This image is too large to preview. Download it instead.' };
return { kind: 'image', dataUrl: `data:${mimeType};base64,${attachment.content.toString('base64')}` };
}
if (mimeType.startsWith('text/') || ['application/json', 'application/xml'].includes(mimeType)) {
return { kind: 'text', text: attachment.content.subarray(0, 100000).toString('utf8'), truncated: size > 100000 };
}
return { kind: 'none', reason: 'No preview is available for this file type. Download it to open it.' };
} finally {
lock.release();
}
} finally {
if (client.usable) await client.logout().catch(() => {});
}
});
ipcMain.handle('pgp:list', () => pgpKeys.list());
ipcMain.handle('pgp:generate', (_event, input) => pgpKeys.generate({
name: input?.name, email: input?.email, passphrase: input?.passphrase, accountId: input?.accountId || null
}));
ipcMain.handle('pgp:import', async (event, input) => {
let armoredKey = input?.armoredKey;
if (!armoredKey) {
const result = await dialog.showOpenDialog(BrowserWindow.fromWebContents(event.sender), {
properties: ['openFile'], filters: [{ name: 'OpenPGP keys', extensions: ['asc', 'gpg', 'pgp', 'key', 'txt'] }]
});
if (result.canceled || !result.filePaths[0]) return { canceled: true };
const stat = await fs.stat(result.filePaths[0]);
if (stat.size > 200000) throw new Error('That key file is too large.');
armoredKey = await fs.readFile(result.filePaths[0], 'utf8');
}
return { key: await pgpKeys.import({ armoredKey, passphrase: input?.passphrase, accountId: input?.accountId || null }) };
});
async function saveKeyFile(event, defaultName, content) {
const result = await dialog.showSaveDialog(BrowserWindow.fromWebContents(event.sender), { defaultPath: defaultName });
if (result.canceled || !result.filePath) return { canceled: true };
await fs.writeFile(result.filePath, content, { mode: 0o600 });
return { saved: true };
}
const pgpFingerprint = value => {
const fingerprint = String(value || '').toUpperCase();
if (!/^[0-9A-F]{40,64}$/.test(fingerprint)) throw new Error('That key could not be identified.');
return fingerprint;
};
ipcMain.handle('pgp:export-public', async (event, fingerprint) => {
const id = pgpFingerprint(fingerprint);
return saveKeyFile(event, `ep-mail-public-${id.slice(-16)}.asc`, await pgpKeys.exportPublic(id));
});
ipcMain.handle('pgp:export-private', async (event, fingerprint, passphrase) => {
const id = pgpFingerprint(fingerprint);
return saveKeyFile(event, `ep-mail-private-${id.slice(-16)}.asc`, await pgpKeys.exportPrivate(id, passphrase));
});
ipcMain.handle('pgp:export-revocation', async (event, fingerprint, passphrase) => {
const id = pgpFingerprint(fingerprint);
return saveKeyFile(event, `ep-mail-revocation-${id.slice(-16)}.asc`, await pgpKeys.exportRevocation(id, passphrase));
});
ipcMain.handle('pgp:delete', (_event, fingerprint, passphrase) => pgpKeys.remove(pgpFingerprint(fingerprint), passphrase));
ipcMain.handle('mail:open-external', async (event, rawUrl) => {
let target;
try {
+151
View File
@@ -0,0 +1,151 @@
const openpgp = require('openpgp');
const MAX_KEY_LENGTH = 200000;
function publicInfo(entry) {
return {
fingerprint: entry.fingerprint,
name: entry.name,
email: entry.email,
accountId: entry.accountId || null,
createdAt: entry.createdAt,
algorithm: entry.algorithm,
hasRevocationCertificate: Boolean(entry.revocationCertificate)
};
}
function requirePassphrase(passphrase) {
if (typeof passphrase !== 'string' || passphrase.length < 8) {
throw new Error('Use a passphrase of at least 8 characters.');
}
return passphrase;
}
function readArmored(value) {
const armored = String(value || '').trim();
if (!armored || armored.length > MAX_KEY_LENGTH) throw new Error('That key file is empty or too large.');
return armored;
}
async function unlock(armoredPrivateKey, passphrase) {
try {
return await openpgp.decryptKey({
privateKey: await openpgp.readPrivateKey({ armoredKey: armoredPrivateKey }),
passphrase
});
} catch {
throw new Error('The passphrase is incorrect.');
}
}
// Passphrase-protected OpenPGP key storage. `storage` persists one JSON object
// (the desktop app wraps it with the OS credential store before writing it).
function createKeyStore(storage) {
async function read() {
const data = await storage.load();
return { keys: Array.isArray(data?.keys) ? data.keys : [] };
}
async function add(entry) {
const data = await read();
if (data.keys.some(key => key.fingerprint === entry.fingerprint)) {
throw new Error('That key is already in your keyring.');
}
data.keys.push(entry);
await storage.save(data);
}
return {
async list() {
return (await read()).keys.map(publicInfo);
},
async generate({ name, email, passphrase, accountId = null }) {
const cleanName = String(name || '').trim().slice(0, 100);
const cleanEmail = String(email || '').trim();
if (!/^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/.test(cleanEmail)) throw new Error('Enter a valid email address for the key.');
requirePassphrase(passphrase);
const { privateKey, publicKey, revocationCertificate } = await openpgp.generateKey({
type: 'curve25519',
userIDs: [{ name: cleanName || undefined, email: cleanEmail }],
passphrase,
format: 'armored'
});
const key = await openpgp.readKey({ armoredKey: publicKey });
const entry = {
fingerprint: key.getFingerprint().toUpperCase(),
name: cleanName,
email: cleanEmail,
accountId,
createdAt: Date.now(),
algorithm: 'Curve25519',
privateKey,
publicKey,
revocationCertificate
};
await add(entry);
return { key: publicInfo(entry), revocationCertificate };
},
async import({ armoredKey, passphrase, accountId = null }) {
const parsed = await openpgp.readPrivateKey({ armoredKey: readArmored(armoredKey) }).catch(() => {
throw new Error('That is not a valid OpenPGP private key.');
});
requirePassphrase(passphrase);
let protectedKey;
if (parsed.isDecrypted()) {
protectedKey = await openpgp.encryptKey({ privateKey: parsed, passphrase });
} else {
await unlock(parsed.armor(), passphrase);
protectedKey = parsed;
}
const user = await protectedKey.getPrimaryUser().catch(() => null);
const entry = {
fingerprint: protectedKey.getFingerprint().toUpperCase(),
name: user?.user?.userID?.name || '',
email: user?.user?.userID?.email || '',
accountId,
createdAt: protectedKey.getCreationTime().getTime(),
algorithm: protectedKey.getAlgorithmInfo().algorithm,
privateKey: protectedKey.armor(),
publicKey: protectedKey.toPublic().armor(),
revocationCertificate: null
};
await add(entry);
return publicInfo(entry);
},
async exportPublic(fingerprint) {
const entry = (await read()).keys.find(key => key.fingerprint === fingerprint);
if (!entry) throw new Error('That key was not found.');
return entry.publicKey;
},
async exportPrivate(fingerprint, passphrase) {
const entry = (await read()).keys.find(key => key.fingerprint === fingerprint);
if (!entry) throw new Error('That key was not found.');
await unlock(entry.privateKey, passphrase);
return entry.privateKey;
},
async exportRevocation(fingerprint, passphrase) {
const entry = (await read()).keys.find(key => key.fingerprint === fingerprint);
if (!entry) throw new Error('That key was not found.');
if (!entry.revocationCertificate) throw new Error('No revocation certificate is stored for this key.');
await unlock(entry.privateKey, passphrase);
return entry.revocationCertificate;
},
async remove(fingerprint, passphrase) {
const data = await read();
const entry = data.keys.find(key => key.fingerprint === fingerprint);
if (!entry) throw new Error('That key was not found.');
await unlock(entry.privateKey, passphrase);
data.keys = data.keys.filter(key => key.fingerprint !== fingerprint);
await storage.save(data);
return { removed: true };
}
};
}
module.exports = { createKeyStore };
+10
View File
@@ -18,10 +18,20 @@ contextBridge.exposeInMainWorld('daybreakMail', {
onSyncUpdate: callback => ipcRenderer.on('mail:sync-update', (_event, update) => callback(update)),
updateMessage: details => ipcRenderer.invoke('mail:update-message', details),
setSnooze: details => ipcRenderer.invoke('mail:set-snooze', details),
previewAttachment: details => ipcRenderer.invoke('mail:preview-attachment', details),
saveAttachment: details => ipcRenderer.invoke('mail:save-attachment', details),
openExternal: url => ipcRenderer.invoke('mail:open-external', url),
send: message => ipcRenderer.invoke('mail:send', message),
disconnect: id => ipcRenderer.invoke('mail:disconnect', id),
pgp: {
list: () => ipcRenderer.invoke('pgp:list'),
generate: details => ipcRenderer.invoke('pgp:generate', details),
importKey: details => ipcRenderer.invoke('pgp:import', details),
exportPublic: fingerprint => ipcRenderer.invoke('pgp:export-public', fingerprint),
exportPrivate: (fingerprint, passphrase) => ipcRenderer.invoke('pgp:export-private', fingerprint, passphrase),
exportRevocation: (fingerprint, passphrase) => ipcRenderer.invoke('pgp:export-revocation', fingerprint, passphrase),
remove: (fingerprint, passphrase) => ipcRenderer.invoke('pgp:delete', fingerprint, passphrase)
},
davList: () => ipcRenderer.invoke('dav:list'),
davConnect: config => ipcRenderer.invoke('dav:connect', config),
davActivate: (type, id) => ipcRenderer.invoke('dav:activate', { type, id }),
+4
View File
@@ -33,6 +33,7 @@
<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>
</nav>
<button class="label-link" id="attachments-nav"><span class="nav-glyph">▤</span>Attachments</button>
<div class="section-label"><span>FOLDERS</span><button class="folder-add" id="add-folder" aria-label="Create folder">+</button></div>
<div id="custom-folders" class="folder-nav"></div>
<div class="sidebar-divider"></div>
@@ -70,5 +71,8 @@
<script src="snooze-ui.js"></script>
<script src="account-ui.js"></script>
<script src="dav-ui.js"></script>
<script src="shortcuts.js"></script>
<script src="attachments.js"></script>
<script src="pgp-ui.js"></script>
</body>
</html>
+21 -2
View File
@@ -1,12 +1,12 @@
{
"name": "ep-mail",
"version": "0.2.0",
"version": "0.2.4",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "ep-mail",
"version": "0.2.0",
"version": "0.2.4",
"dependencies": {
"@capacitor/android": "^8.5.2",
"@capacitor/core": "^8.5.2",
@@ -14,6 +14,7 @@
"imapflow": "2.2.1",
"mailparser": "3.9.33",
"nodemailer": "10.0.9",
"openpgp": "^6.3.2",
"tsdav": "^2.3.4"
},
"devDependencies": {
@@ -3976,6 +3977,24 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/openpgp": {
"version": "6.3.2",
"resolved": "https://registry.npmjs.org/openpgp/-/openpgp-6.3.2.tgz",
"integrity": "sha512-wcZTzHz41LV8Y48zH/JlD1JT8YdNmpWOuMAjQ/podvvCwsjBEU37K3znJh4UQcj3hksE5z9TzvhbUbwzsGvlLQ==",
"license": "LGPL-3.0+",
"engines": {
"node": ">= 18.0.0",
"typescript": ">= 5.0.0"
},
"peerDependencies": {
"@openpgp/web-stream-tools": "~0.3.0"
},
"peerDependenciesMeta": {
"@openpgp/web-stream-tools": {
"optional": true
}
}
},
"node_modules/p-cancelable": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/p-cancelable/-/p-cancelable-2.1.1.tgz",
+6 -1
View File
@@ -1,6 +1,6 @@
{
"name": "ep-mail",
"version": "0.2.0",
"version": "0.2.4",
"private": true,
"description": "Eternity Project mail client",
"author": "Eternity Project",
@@ -16,6 +16,7 @@
"dist:linux:appimage": "electron-builder --linux AppImage",
"dist:linux:deb": "electron-builder --linux deb",
"bump:build": "npm version patch --no-git-tag-version",
"test": "node --test tests/",
"build:android-web": "node scripts/prepare-android-web.cjs",
"android:sync": "npm run build:android-web && cap sync android",
"android:open": "npm run android:sync && cap open android",
@@ -41,6 +42,9 @@
"productivity.js",
"account-ui.js",
"dav-ui.js",
"shortcuts.js",
"attachments.js",
"pgp-ui.js",
"icon.svg",
"logo-ep-daylight.svg",
"logo-ep-wasteland.svg",
@@ -85,6 +89,7 @@
"imapflow": "2.2.1",
"mailparser": "3.9.33",
"nodemailer": "10.0.9",
"openpgp": "^6.3.2",
"tsdav": "^2.3.4"
}
}
+114
View File
@@ -0,0 +1,114 @@
// Encryption key management (desktop). Hidden where the platform has no key store yet.
function pgpAvailable() { return Boolean(window.daybreakMail?.pgp); }
function openEncryptionKeys() {
const root = $('#modal-root');
const account = connectedMailAccount || {};
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. Sending and reading encrypted mail is not available yet.</p>
<div id="pgp-key-list" class="attachment-list">Loading keys…</div>
<h3 class="pgp-heading">Create a key</h3>
<label class="compose-line"><span>Name</span><input id="pgp-name" maxlength="100" value="${esc(account.displayName || '')}"></label>
<label class="compose-line"><span>Email</span><input id="pgp-email" type="email" value="${esc(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>
<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>
</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(); };
const status = message => { $('#pgp-status').textContent = message; };
const passphraseField = () => $('#pgp-passphrase');
const needPassphrase = () => {
const value = passphraseField().value;
if (!value) { status('Enter the key passphrase in the Passphrase field first.'); passphraseField().focus(); }
return value;
};
async function render() {
const list = $('#pgp-key-list');
let keys = [];
try { keys = await window.daybreakMail.pgp.list(); } catch (error) { list.textContent = error.message || 'Could not load keys.'; return; }
list.replaceChildren();
if (!keys.length) { list.textContent = 'No keys yet.'; return; }
keys.forEach(key => {
const row = document.createElement('div');
row.className = 'attachment-row';
const info = document.createElement('div');
info.className = 'attachment-row-info';
const title = document.createElement('strong');
title.textContent = key.email || 'OpenPGP key';
const meta = document.createElement('small');
meta.textContent = `${key.name ? key.name + ' · ' : ''}${key.algorithm} · ${new Date(key.createdAt).toLocaleDateString()}`;
const fingerprint = document.createElement('small');
fingerprint.textContent = `Fingerprint: ${key.fingerprint.match(/.{1,4}/g).join(' ')}`;
info.append(title, meta, fingerprint);
row.append(info);
const actions = [
['Export public', () => window.daybreakMail.pgp.exportPublic(key.fingerprint), false],
['Export private', () => window.daybreakMail.pgp.exportPrivate(key.fingerprint, needPassphrase()), true]
];
if (key.hasRevocationCertificate) actions.push(['Revocation cert.', () => window.daybreakMail.pgp.exportRevocation(key.fingerprint, needPassphrase()), true]);
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 };
await window.daybreakMail.pgp.remove(key.fingerprint, needPassphrase());
await render();
return { deleted: true };
}, true]);
actions.forEach(([label, run, secret]) => {
const button = document.createElement('button');
button.className = 'discard';
button.textContent = label;
button.onclick = async () => {
if (secret && !passphraseField().value) { needPassphrase(); return; }
try {
const result = await run();
status(result?.saved ? 'File saved.' : result?.deleted ? 'Key deleted.' : '');
} catch (error) { status(error.message || 'That action failed.'); }
};
row.append(button);
});
list.append(row);
});
}
$('#pgp-generate').onclick = async () => {
const button = $('#pgp-generate');
button.disabled = true;
status('Creating key…');
try {
await window.daybreakMail.pgp.generate({
name: $('#pgp-name').value, email: $('#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.');
await render();
} catch (error) { status(error.message || 'Could not create the key.'); }
button.disabled = false;
};
$('#pgp-import').onclick = async () => {
const passphrase = needPassphrase();
if (!passphrase) return;
try {
const result = await window.daybreakMail.pgp.importKey({ passphrase, accountId: account.id || null });
status(result.canceled ? '' : 'Key imported.');
await render();
} catch (error) { status(error.message || 'Could not import the key.'); }
};
void render();
}
if (typeof openPreferences === 'function') {
const baseOpenPreferences = openPreferences;
openPreferences = function () {
baseOpenPreferences();
const fields = $('#modal-root .compose-fields');
if (!fields || !pgpAvailable()) return;
const button = document.createElement('button');
button.type = 'button';
button.className = 'discard';
button.id = 'open-encryption-keys';
button.textContent = 'Encryption keys…';
button.onclick = openEncryptionKeys;
fields.append(button);
};
}
+1
View File
@@ -530,6 +530,7 @@
updateMessage: (details) => EpMail.updateMessage(details),
setSnooze: (details) => EpMail.setSnooze(details),
checkSnoozeReminders: () => EpMail.checkSnoozeReminders(),
previewAttachment: (details) => EpMail.previewAttachment(details),
saveAttachment: (details) => EpMail.saveAttachment(details),
openExternal: (url) => EpMail.openExternal({ url }),
send: (message) => EpMail.send(message),
+1
View File
@@ -22,6 +22,7 @@ if (Capacitor.isNativePlatform() && Capacitor.getPlatform() === 'android') {
updateMessage: details => EpMail.updateMessage(details),
setSnooze: details => EpMail.setSnooze(details),
checkSnoozeReminders: () => EpMail.checkSnoozeReminders(),
previewAttachment: details => EpMail.previewAttachment(details),
saveAttachment: details => EpMail.saveAttachment(details),
openExternal: url => EpMail.openExternal({ url }),
send: message => EpMail.send(message),
+3
View File
@@ -13,6 +13,9 @@ const assets = [
'productivity.js',
'account-ui.js',
'dav-ui.js',
'shortcuts.js',
'attachments.js',
'pgp-ui.js',
'icon.svg',
'logo-ep-daylight.svg',
'logo-ep-wasteland.svg',
+2 -2
View File
@@ -1,5 +1,5 @@
const CACHE='ep-mail-v3';
const FILES=['./','./index.html','./styles.css','./branding.css','./app.js','./platform-bridge.js','./mail-ui.js','./productivity.js','./snooze-ui.js','./account-ui.js','./dav-ui.js','./manifest.webmanifest','./icon.svg','./logo-ep-daylight.svg','./logo-ep-wasteland.svg'];
const CACHE='ep-mail-v6';
const FILES=['./','./index.html','./styles.css','./branding.css','./app.js','./platform-bridge.js','./mail-ui.js','./productivity.js','./snooze-ui.js','./account-ui.js','./dav-ui.js','./shortcuts.js','./attachments.js','./pgp-ui.js','./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('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'))))});
+102
View File
@@ -0,0 +1,102 @@
// Configurable keyboard shortcuts for common mail actions.
const shortcutStorageKey = 'daybreak-shortcuts';
const shortcutActions = [
{ id: 'compose', label: 'Compose', fallback: 'c', run: () => $('#compose')?.click() },
{ id: 'search', label: 'Search', fallback: '/', run: () => $('#search')?.focus() },
{ id: 'refresh', label: 'Refresh', fallback: 'r', run: () => $('#refresh')?.click() },
{ id: 'archive', label: 'Archive message', fallback: 'e', run: () => $('#reader-archive')?.click() },
{ id: 'delete', label: 'Delete message', fallback: '#', run: () => $('#reader-delete')?.click() },
{ id: 'star', label: 'Star message', fallback: 's', run: () => $('#reader-star')?.click() },
{ id: 'reply', label: 'Reply', fallback: 'a', run: () => $('#reply')?.click() },
{ id: 'forward', label: 'Forward', fallback: 'f', run: () => $('#forward')?.click() },
{ id: 'next', label: 'Next message', fallback: 'j', run: () => moveMessageSelection(1) },
{ id: 'previous', label: 'Previous message', fallback: 'k', run: () => moveMessageSelection(-1) }
];
function normalizeShortcut(value) {
const text = String(value || '').trim();
if (!text) return '';
const parts = text.split('+').map(part => part.trim()).filter(Boolean);
const key = parts.pop() || '+';
const mods = ['Ctrl', 'Alt', 'Shift'].filter(mod => parts.some(part => part.toLowerCase() === mod.toLowerCase()));
return [...mods, key.length === 1 ? key.toLowerCase() : key].join('+');
}
function loadShortcuts() {
let saved = {};
try { saved = JSON.parse(localStorage.getItem(shortcutStorageKey)) || {}; } catch {}
return Object.fromEntries(shortcutActions.map(action => [
action.id, typeof saved[action.id] === 'string' ? normalizeShortcut(saved[action.id]) : action.fallback
]));
}
function eventShortcut(event) {
if (['Control', 'Alt', 'Shift', 'Meta'].includes(event.key)) return '';
const mods = [event.ctrlKey || event.metaKey ? 'Ctrl' : '', event.altKey ? 'Alt' : ''];
const printable = event.key.length === 1;
if (event.shiftKey && !printable) mods.push('Shift');
return normalizeShortcut([...mods.filter(Boolean), event.key === ' ' ? 'Space' : event.key].join('+'));
}
function moveMessageSelection(step) {
if (!messages.length) return;
const index = messages.findIndex(message => message.id === activeMessage);
const next = messages[Math.min(messages.length - 1, Math.max(0, index + step))];
if (next) { openMessage(next.id); $(`.message[data-id="${next.id}"]`)?.scrollIntoView({ block: 'nearest' }); }
}
document.addEventListener('keydown', event => {
if (event.defaultPrevented || event.isComposing || event.key === 'Escape') return;
const target = event.target;
if (target?.closest?.('input, textarea, select, [contenteditable="true"]') || $('#modal-root')?.children.length) return;
const pressed = eventShortcut(event);
if (!pressed) return;
const shortcuts = loadShortcuts();
const action = shortcutActions.find(item => shortcuts[item.id] && shortcuts[item.id] === pressed);
if (!action) return;
event.preventDefault();
action.run();
});
if (typeof openPreferences === 'function') {
const baseOpenPreferences = openPreferences;
openPreferences = function () {
baseOpenPreferences();
const fields = $('#modal-root .compose-fields');
const save = $('#save-appearance');
if (!fields || !save) return;
const shortcuts = loadShortcuts();
const section = document.createElement('div');
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 =>
`<label class="compose-line"><span>${action.label}</span><input class="shortcut-input" data-action="${action.id}" maxlength="24" value="${esc(shortcuts[action.id])}" placeholder="None"></label>`).join('')}<button type="button" class="discard" id="reset-shortcuts">Reset to defaults</button>`;
fields.append(section);
section.addEventListener('keydown', event => {
const input = event.target.closest('.shortcut-input');
if (!input || ['Tab', 'Escape'].includes(event.key)) return;
event.preventDefault();
if (['Backspace', 'Delete'].includes(event.key)) { input.value = ''; return; }
const combo = eventShortcut(event);
if (combo) input.value = combo;
});
$('#reset-shortcuts').onclick = () => {
section.querySelectorAll('.shortcut-input').forEach(input => {
input.value = shortcutActions.find(action => action.id === input.dataset.action).fallback;
});
};
const baseSave = save.onclick;
save.onclick = event => {
const values = {};
const used = new Map();
for (const input of section.querySelectorAll('.shortcut-input')) {
const value = normalizeShortcut(input.value);
const label = shortcutActions.find(action => action.id === input.dataset.action).label;
if (value && used.has(value)) { toast(`“${value}” is used by both ${used.get(value)} and ${label}`); return; }
if (value) used.set(value, label);
values[input.dataset.action] = value;
}
localStorage.setItem(shortcutStorageKey, JSON.stringify(values));
baseSave?.call(save, event);
};
};
}
+3
View File
@@ -126,3 +126,6 @@ body.ep-daylight .row-check:checked{accent-color:#526a2c}
body.ep-daylight .mail-safety-warning{background:#fff6df;color:#5b3c17}body.ep-daylight .mail-link-risky{background:#fff8ea;border-color:#d69b43}
.folder-add{border:0;background:transparent;color:#929990;font-size:18px;cursor:pointer}.folder-add:hover{color:#487354}.section-label+.folder-nav:empty{display:none}.custom-folder span:last-child{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.shortcut-settings h3{margin:16px 0 4px;font-size:13px}.shortcut-settings code{font-family:monospace}.shortcut-input{text-transform:none}.shortcut-settings #reset-shortcuts{margin-top:8px}
.attachments-modal{width:min(720px,94vw)}.attachment-toolbar{display:flex;gap:8px;margin-bottom:10px}.attachment-toolbar input{flex:1}.attachment-list{max-height:60vh;overflow:auto;display:grid;gap:8px}.attachment-row{display:flex;flex-wrap:wrap;gap:8px;align-items:center;padding:8px;border:1px solid var(--line);border-radius:8px}.attachment-row-info{flex:1;min-width:0;display:flex;flex-direction:column;gap:2px}.attachment-row-info strong,.attachment-row-info small{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.attachment-preview{flex-basis:100%;max-height:320px;overflow:auto;padding:8px;font-size:12px}.attachment-preview-image{max-width:100%;max-height:300px;display:block}.attachment-preview-text{margin:0;white-space:pre-wrap;word-break:break-word}.preview-attachment{font-size:14px}
.pgp-heading{margin:16px 0 4px;font-size:13px}.pgp-actions{display:flex;gap:8px;margin-top:8px}#open-encryption-keys{margin-top:12px}
+77
View File
@@ -0,0 +1,77 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const openpgp = require('openpgp');
const { createKeyStore } = require('../desktop/pgp-keystore.cjs');
function memoryStore() {
let data = null;
return { load: async () => data, save: async value => { data = JSON.parse(JSON.stringify(value)); } };
}
const passphrase = 'correct horse battery';
test('generates a passphrase-protected key and never lists secrets', async () => {
const storage = memoryStore();
const keys = createKeyStore(storage);
const { key, revocationCertificate } = await keys.generate({ name: 'Ada', email: 'ada@example.com', passphrase });
assert.match(key.fingerprint, /^[0-9A-F]{40,64}$/);
assert.ok(revocationCertificate.includes('BEGIN PGP PUBLIC KEY BLOCK'));
const listed = await keys.list();
assert.equal(listed.length, 1);
assert.equal(JSON.stringify(listed).includes('PRIVATE'), false);
const stored = (await storage.load()).keys[0];
const parsed = await openpgp.readPrivateKey({ armoredKey: stored.privateKey });
assert.equal(parsed.isDecrypted(), false);
});
test('rejects weak passphrases and bad addresses', async () => {
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: 'nope', passphrase }), /valid email/);
});
test('export requires the right passphrase and round-trips through import', async () => {
const first = createKeyStore(memoryStore());
const { key } = await first.generate({ name: 'Ada', email: 'ada@example.com', passphrase });
await assert.rejects(first.exportPrivate(key.fingerprint, 'wrong passphrase'), /incorrect/);
const armored = await first.exportPrivate(key.fingerprint, passphrase);
const second = createKeyStore(memoryStore());
const imported = await second.import({ armoredKey: armored, passphrase });
assert.equal(imported.fingerprint, key.fingerprint);
assert.equal(imported.email, 'ada@example.com');
await assert.rejects(second.import({ armoredKey: armored, passphrase }), /already/);
assert.ok((await second.exportPublic(key.fingerprint)).includes('BEGIN PGP PUBLIC KEY BLOCK'));
});
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 keys = createKeyStore(memoryStore());
const imported = await keys.import({ armoredKey: privateKey, passphrase });
const exported = await keys.exportPrivate(imported.fingerprint, passphrase);
assert.equal((await openpgp.readPrivateKey({ armoredKey: exported })).isDecrypted(), false);
});
test('rejects invalid key material and a wrong passphrase on import', async () => {
const keys = createKeyStore(memoryStore());
await assert.rejects(keys.import({ armoredKey: 'not a key', passphrase }), /valid OpenPGP/);
const source = createKeyStore(memoryStore());
const { key } = await source.generate({ name: 'C', email: 'c@example.com', passphrase });
const armored = await source.exportPrivate(key.fingerprint, passphrase);
await assert.rejects(keys.import({ armoredKey: armored, passphrase: 'another passphrase' }), /incorrect/);
});
test('deleting a key needs the passphrase', async () => {
const keys = createKeyStore(memoryStore());
const { key } = await keys.generate({ name: 'D', email: 'd@example.com', passphrase });
await assert.rejects(keys.remove(key.fingerprint, 'wrong passphrase'), /incorrect/);
assert.equal((await keys.list()).length, 1);
await keys.remove(key.fingerprint, passphrase);
assert.equal((await keys.list()).length, 0);
});
test('stored revocation certificate is returned only after unlocking', async () => {
const keys = createKeyStore(memoryStore());
const { key } = await keys.generate({ name: 'E', email: 'e@example.com', passphrase });
await assert.rejects(keys.exportRevocation(key.fingerprint, 'wrong passphrase'), /incorrect/);
assert.ok((await keys.exportRevocation(key.fingerprint, passphrase)).includes('BEGIN PGP PUBLIC KEY BLOCK'));
});
+161
View File
@@ -0,0 +1,161 @@
// Attachment previews and a dedicated view for finding and managing attachments across mailboxes.
const attachmentFolders = ['Inbox', 'Sent', 'Archive', 'Trash'];
let attachmentItems = [];
function attachmentKind(filename) {
const ext = String(filename).toLowerCase().split('.').pop();
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 (['zip', 'rar', '7z', 'tar', 'gz'].includes(ext)) return 'Archives';
return 'Other';
}
function attachmentSize(size) {
if (!size) return '';
if (typeof size === 'string') return size;
return size < 1048576 ? `${Math.max(1, Math.round(size / 1024))} KB` : `${(size / 1048576).toFixed(1)} MB`;
}
async function previewAttachment(target, details) {
if (!details.uid || !window.daybreakMail?.previewAttachment) {
target.textContent = 'Previews are available for connected mailbox messages.';
return;
}
target.textContent = 'Loading preview…';
try {
const result = await window.daybreakMail.previewAttachment(details);
target.replaceChildren();
if (result.kind === 'image') {
const image = document.createElement('img');
image.className = 'attachment-preview-image';
image.alt = details.filename;
image.src = result.dataUrl;
target.append(image);
} else if (result.kind === 'text') {
const pre = document.createElement('pre');
pre.className = 'attachment-preview-text';
pre.textContent = result.text + (result.truncated ? '\n… (preview truncated)' : '');
target.append(pre);
} else {
target.textContent = result.reason || 'No preview is available for this file type.';
}
} catch (error) {
target.textContent = error.message || 'Could not load the preview.';
}
}
function downloadAttachment(details) {
if (!details.uid || !window.daybreakMail?.saveAttachment) { toast('Attachment download is available for connected mailbox messages'); return; }
window.daybreakMail.saveAttachment(details)
.then(result => { if (result.saved) toast('Attachment saved'); })
.catch(error => toast(error.message || 'Could not save attachment'));
}
// Add a Preview button to each attachment in the reader.
if (typeof openMessage === 'function') {
const baseOpenMessage = openMessage;
openMessage = function (id) {
baseOpenMessage(id);
const message = messages.find(item => item.id === id);
if (!message?.uid) return;
$$('#reader-pane .attachment').forEach(row => {
const download = row.querySelector('.download');
if (!download || row.querySelector('.preview-attachment')) return;
const button = document.createElement('button');
button.className = 'preview-attachment icon-button';
button.title = 'Preview';
button.setAttribute('aria-label', `Preview ${download.dataset.filename}`);
button.textContent = '👁';
button.addEventListener('click', event => {
event.stopPropagation();
let panel = row.nextElementSibling?.classList.contains('attachment-preview') ? row.nextElementSibling : null;
if (panel) { panel.remove(); return; }
panel = document.createElement('div');
panel.className = 'attachment-preview';
row.after(panel);
void previewAttachment(panel, { uid: message.uid, folder: message.sourceFolder || activeFolder, filename: download.dataset.filename });
});
download.before(button);
});
};
}
async function collectAttachments() {
const items = [];
for (const folder of attachmentFolders) {
let offset = 0;
for (let page = 0; page < 5; page += 1) {
const result = await window.daybreakMail.syncFolder(folder, offset, { hasAttachments: true });
for (const message of result.messages || []) {
for (const file of message.attachments || []) {
items.push({
uid: message.uid, folder, filename: file.filename, size: file.size,
subject: message.subject, sender: message.sender, date: message.date, timestamp: Number(message.timestamp || 0),
kind: attachmentKind(file.filename)
});
}
}
offset += (result.messages || []).length;
if (!result.messages?.length || offset >= (result.total || 0)) break;
}
}
return items.sort((a, b) => b.timestamp - a.timestamp);
}
async function openAttachmentsView() {
if (!connectedMailAccount || !window.daybreakMail) { openMailAccount(); return; }
const root = $('#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>`;
const close = () => { root.innerHTML = ''; };
root.querySelector('.modal-close').onclick = close;
root.querySelector('.modal-overlay').onclick = event => { if (event.target.classList.contains('modal-overlay')) close(); };
const list = $('#attachment-list');
const render = () => {
const text = $('#attachment-search').value.trim().toLowerCase();
const type = $('#attachment-type').value;
const shown = attachmentItems.filter(item => (!type || item.kind === type) &&
(!text || `${item.filename} ${item.subject} ${item.sender}`.toLowerCase().includes(text)));
list.replaceChildren();
if (!shown.length) { list.textContent = attachmentItems.length ? 'No attachments match.' : 'No attachments found.'; return; }
shown.forEach(item => {
const row = document.createElement('div');
row.className = 'attachment-row';
const info = document.createElement('div');
info.className = 'attachment-row-info';
const name = document.createElement('strong');
name.textContent = item.filename;
const meta = document.createElement('small');
meta.textContent = [attachmentSize(item.size), item.sender, item.subject, item.folder, item.date].filter(Boolean).join(' · ');
info.append(name, meta);
const preview = document.createElement('button');
preview.className = 'discard';
preview.textContent = 'Preview';
const save = document.createElement('button');
save.className = 'discard';
save.textContent = 'Download';
const panel = document.createElement('div');
panel.className = 'attachment-preview';
panel.hidden = true;
const details = { uid: item.uid, folder: item.folder, filename: item.filename };
preview.onclick = () => {
panel.hidden = !panel.hidden;
if (!panel.hidden && !panel.childElementCount && !panel.textContent) void previewAttachment(panel, details);
};
save.onclick = () => downloadAttachment(details);
row.append(info, preview, save, panel);
list.append(row);
});
};
$('#attachment-search').oninput = render;
$('#attachment-type').onchange = render;
try {
attachmentItems = await collectAttachments();
if ($('#attachment-list')) render();
} catch (error) {
if ($('#attachment-list')) $('#attachment-list').textContent = error.message || 'Could not load attachments.';
}
}
document.addEventListener('DOMContentLoaded', () => {
$('#attachments-nav')?.addEventListener('click', openAttachmentsView);
});
+4
View File
@@ -33,6 +33,7 @@
<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>
</nav>
<button class="label-link" id="attachments-nav"><span class="nav-glyph">▤</span>Attachments</button>
<div class="section-label"><span>FOLDERS</span><button class="folder-add" id="add-folder" aria-label="Create folder">+</button></div>
<div id="custom-folders" class="folder-nav"></div>
<div class="sidebar-divider"></div>
@@ -70,5 +71,8 @@
<script src="snooze-ui.js"></script>
<script src="account-ui.js"></script>
<script src="dav-ui.js"></script>
<script src="shortcuts.js"></script>
<script src="attachments.js"></script>
<script src="pgp-ui.js"></script>
</body>
</html>
+114
View File
@@ -0,0 +1,114 @@
// Encryption key management (desktop). Hidden where the platform has no key store yet.
function pgpAvailable() { return Boolean(window.daybreakMail?.pgp); }
function openEncryptionKeys() {
const root = $('#modal-root');
const account = connectedMailAccount || {};
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. Sending and reading encrypted mail is not available yet.</p>
<div id="pgp-key-list" class="attachment-list">Loading keys…</div>
<h3 class="pgp-heading">Create a key</h3>
<label class="compose-line"><span>Name</span><input id="pgp-name" maxlength="100" value="${esc(account.displayName || '')}"></label>
<label class="compose-line"><span>Email</span><input id="pgp-email" type="email" value="${esc(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>
<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>
</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(); };
const status = message => { $('#pgp-status').textContent = message; };
const passphraseField = () => $('#pgp-passphrase');
const needPassphrase = () => {
const value = passphraseField().value;
if (!value) { status('Enter the key passphrase in the Passphrase field first.'); passphraseField().focus(); }
return value;
};
async function render() {
const list = $('#pgp-key-list');
let keys = [];
try { keys = await window.daybreakMail.pgp.list(); } catch (error) { list.textContent = error.message || 'Could not load keys.'; return; }
list.replaceChildren();
if (!keys.length) { list.textContent = 'No keys yet.'; return; }
keys.forEach(key => {
const row = document.createElement('div');
row.className = 'attachment-row';
const info = document.createElement('div');
info.className = 'attachment-row-info';
const title = document.createElement('strong');
title.textContent = key.email || 'OpenPGP key';
const meta = document.createElement('small');
meta.textContent = `${key.name ? key.name + ' · ' : ''}${key.algorithm} · ${new Date(key.createdAt).toLocaleDateString()}`;
const fingerprint = document.createElement('small');
fingerprint.textContent = `Fingerprint: ${key.fingerprint.match(/.{1,4}/g).join(' ')}`;
info.append(title, meta, fingerprint);
row.append(info);
const actions = [
['Export public', () => window.daybreakMail.pgp.exportPublic(key.fingerprint), false],
['Export private', () => window.daybreakMail.pgp.exportPrivate(key.fingerprint, needPassphrase()), true]
];
if (key.hasRevocationCertificate) actions.push(['Revocation cert.', () => window.daybreakMail.pgp.exportRevocation(key.fingerprint, needPassphrase()), true]);
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 };
await window.daybreakMail.pgp.remove(key.fingerprint, needPassphrase());
await render();
return { deleted: true };
}, true]);
actions.forEach(([label, run, secret]) => {
const button = document.createElement('button');
button.className = 'discard';
button.textContent = label;
button.onclick = async () => {
if (secret && !passphraseField().value) { needPassphrase(); return; }
try {
const result = await run();
status(result?.saved ? 'File saved.' : result?.deleted ? 'Key deleted.' : '');
} catch (error) { status(error.message || 'That action failed.'); }
};
row.append(button);
});
list.append(row);
});
}
$('#pgp-generate').onclick = async () => {
const button = $('#pgp-generate');
button.disabled = true;
status('Creating key…');
try {
await window.daybreakMail.pgp.generate({
name: $('#pgp-name').value, email: $('#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.');
await render();
} catch (error) { status(error.message || 'Could not create the key.'); }
button.disabled = false;
};
$('#pgp-import').onclick = async () => {
const passphrase = needPassphrase();
if (!passphrase) return;
try {
const result = await window.daybreakMail.pgp.importKey({ passphrase, accountId: account.id || null });
status(result.canceled ? '' : 'Key imported.');
await render();
} catch (error) { status(error.message || 'Could not import the key.'); }
};
void render();
}
if (typeof openPreferences === 'function') {
const baseOpenPreferences = openPreferences;
openPreferences = function () {
baseOpenPreferences();
const fields = $('#modal-root .compose-fields');
if (!fields || !pgpAvailable()) return;
const button = document.createElement('button');
button.type = 'button';
button.className = 'discard';
button.id = 'open-encryption-keys';
button.textContent = 'Encryption keys…';
button.onclick = openEncryptionKeys;
fields.append(button);
};
}
+1
View File
@@ -530,6 +530,7 @@
updateMessage: (details) => EpMail.updateMessage(details),
setSnooze: (details) => EpMail.setSnooze(details),
checkSnoozeReminders: () => EpMail.checkSnoozeReminders(),
previewAttachment: (details) => EpMail.previewAttachment(details),
saveAttachment: (details) => EpMail.saveAttachment(details),
openExternal: (url) => EpMail.openExternal({ url }),
send: (message) => EpMail.send(message),
+2 -2
View File
@@ -1,5 +1,5 @@
const CACHE='ep-mail-v3';
const FILES=['./','./index.html','./styles.css','./branding.css','./app.js','./platform-bridge.js','./mail-ui.js','./productivity.js','./snooze-ui.js','./account-ui.js','./dav-ui.js','./manifest.webmanifest','./icon.svg','./logo-ep-daylight.svg','./logo-ep-wasteland.svg'];
const CACHE='ep-mail-v6';
const FILES=['./','./index.html','./styles.css','./branding.css','./app.js','./platform-bridge.js','./mail-ui.js','./productivity.js','./snooze-ui.js','./account-ui.js','./dav-ui.js','./shortcuts.js','./attachments.js','./pgp-ui.js','./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('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'))))});
+102
View File
@@ -0,0 +1,102 @@
// Configurable keyboard shortcuts for common mail actions.
const shortcutStorageKey = 'daybreak-shortcuts';
const shortcutActions = [
{ id: 'compose', label: 'Compose', fallback: 'c', run: () => $('#compose')?.click() },
{ id: 'search', label: 'Search', fallback: '/', run: () => $('#search')?.focus() },
{ id: 'refresh', label: 'Refresh', fallback: 'r', run: () => $('#refresh')?.click() },
{ id: 'archive', label: 'Archive message', fallback: 'e', run: () => $('#reader-archive')?.click() },
{ id: 'delete', label: 'Delete message', fallback: '#', run: () => $('#reader-delete')?.click() },
{ id: 'star', label: 'Star message', fallback: 's', run: () => $('#reader-star')?.click() },
{ id: 'reply', label: 'Reply', fallback: 'a', run: () => $('#reply')?.click() },
{ id: 'forward', label: 'Forward', fallback: 'f', run: () => $('#forward')?.click() },
{ id: 'next', label: 'Next message', fallback: 'j', run: () => moveMessageSelection(1) },
{ id: 'previous', label: 'Previous message', fallback: 'k', run: () => moveMessageSelection(-1) }
];
function normalizeShortcut(value) {
const text = String(value || '').trim();
if (!text) return '';
const parts = text.split('+').map(part => part.trim()).filter(Boolean);
const key = parts.pop() || '+';
const mods = ['Ctrl', 'Alt', 'Shift'].filter(mod => parts.some(part => part.toLowerCase() === mod.toLowerCase()));
return [...mods, key.length === 1 ? key.toLowerCase() : key].join('+');
}
function loadShortcuts() {
let saved = {};
try { saved = JSON.parse(localStorage.getItem(shortcutStorageKey)) || {}; } catch {}
return Object.fromEntries(shortcutActions.map(action => [
action.id, typeof saved[action.id] === 'string' ? normalizeShortcut(saved[action.id]) : action.fallback
]));
}
function eventShortcut(event) {
if (['Control', 'Alt', 'Shift', 'Meta'].includes(event.key)) return '';
const mods = [event.ctrlKey || event.metaKey ? 'Ctrl' : '', event.altKey ? 'Alt' : ''];
const printable = event.key.length === 1;
if (event.shiftKey && !printable) mods.push('Shift');
return normalizeShortcut([...mods.filter(Boolean), event.key === ' ' ? 'Space' : event.key].join('+'));
}
function moveMessageSelection(step) {
if (!messages.length) return;
const index = messages.findIndex(message => message.id === activeMessage);
const next = messages[Math.min(messages.length - 1, Math.max(0, index + step))];
if (next) { openMessage(next.id); $(`.message[data-id="${next.id}"]`)?.scrollIntoView({ block: 'nearest' }); }
}
document.addEventListener('keydown', event => {
if (event.defaultPrevented || event.isComposing || event.key === 'Escape') return;
const target = event.target;
if (target?.closest?.('input, textarea, select, [contenteditable="true"]') || $('#modal-root')?.children.length) return;
const pressed = eventShortcut(event);
if (!pressed) return;
const shortcuts = loadShortcuts();
const action = shortcutActions.find(item => shortcuts[item.id] && shortcuts[item.id] === pressed);
if (!action) return;
event.preventDefault();
action.run();
});
if (typeof openPreferences === 'function') {
const baseOpenPreferences = openPreferences;
openPreferences = function () {
baseOpenPreferences();
const fields = $('#modal-root .compose-fields');
const save = $('#save-appearance');
if (!fields || !save) return;
const shortcuts = loadShortcuts();
const section = document.createElement('div');
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 =>
`<label class="compose-line"><span>${action.label}</span><input class="shortcut-input" data-action="${action.id}" maxlength="24" value="${esc(shortcuts[action.id])}" placeholder="None"></label>`).join('')}<button type="button" class="discard" id="reset-shortcuts">Reset to defaults</button>`;
fields.append(section);
section.addEventListener('keydown', event => {
const input = event.target.closest('.shortcut-input');
if (!input || ['Tab', 'Escape'].includes(event.key)) return;
event.preventDefault();
if (['Backspace', 'Delete'].includes(event.key)) { input.value = ''; return; }
const combo = eventShortcut(event);
if (combo) input.value = combo;
});
$('#reset-shortcuts').onclick = () => {
section.querySelectorAll('.shortcut-input').forEach(input => {
input.value = shortcutActions.find(action => action.id === input.dataset.action).fallback;
});
};
const baseSave = save.onclick;
save.onclick = event => {
const values = {};
const used = new Map();
for (const input of section.querySelectorAll('.shortcut-input')) {
const value = normalizeShortcut(input.value);
const label = shortcutActions.find(action => action.id === input.dataset.action).label;
if (value && used.has(value)) { toast(`“${value}” is used by both ${used.get(value)} and ${label}`); return; }
if (value) used.set(value, label);
values[input.dataset.action] = value;
}
localStorage.setItem(shortcutStorageKey, JSON.stringify(values));
baseSave?.call(save, event);
};
};
}
+3
View File
@@ -126,3 +126,6 @@ body.ep-daylight .row-check:checked{accent-color:#526a2c}
body.ep-daylight .mail-safety-warning{background:#fff6df;color:#5b3c17}body.ep-daylight .mail-link-risky{background:#fff8ea;border-color:#d69b43}
.folder-add{border:0;background:transparent;color:#929990;font-size:18px;cursor:pointer}.folder-add:hover{color:#487354}.section-label+.folder-nav:empty{display:none}.custom-folder span:last-child{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.shortcut-settings h3{margin:16px 0 4px;font-size:13px}.shortcut-settings code{font-family:monospace}.shortcut-input{text-transform:none}.shortcut-settings #reset-shortcuts{margin-top:8px}
.attachments-modal{width:min(720px,94vw)}.attachment-toolbar{display:flex;gap:8px;margin-bottom:10px}.attachment-toolbar input{flex:1}.attachment-list{max-height:60vh;overflow:auto;display:grid;gap:8px}.attachment-row{display:flex;flex-wrap:wrap;gap:8px;align-items:center;padding:8px;border:1px solid var(--line);border-radius:8px}.attachment-row-info{flex:1;min-width:0;display:flex;flex-direction:column;gap:2px}.attachment-row-info strong,.attachment-row-info small{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.attachment-preview{flex-basis:100%;max-height:320px;overflow:auto;padding:8px;font-size:12px}.attachment-preview-image{max-width:100%;max-height:300px;display:block}.attachment-preview-text{margin:0;white-space:pre-wrap;word-break:break-word}.preview-attachment{font-size:14px}
.pgp-heading{margin:16px 0 4px;font-size:13px}.pgp-actions{display:flex;gap:8px;margin-top:8px}#open-encryption-keys{margin-top:12px}