Add OpenPGP mail encryption: decrypt, verify, encrypt, sign and contact keyring, v0.3.0

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
2026-10-07 15:39:51 +03:00
co-authored by Copilot
parent bae9c7966d
commit 750665f96b
23 changed files with 1493 additions and 42 deletions
+16 -7
View File
@@ -1,6 +1,6 @@
# Encryption plan: OpenPGP mail encryption for ep-mail # 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). Status: **Phases 1–3 and the desktop parts of 4–6 are implemented.** Android support, manual interop checks with Thunderbird/GnuPG and an independent security review are still open; see [TODO.md](./TODO.md).
## 1. Format: OpenPGP with PGP/MIME (RFC 3156) ## 1. Format: OpenPGP with PGP/MIME (RFC 3156)
@@ -52,11 +52,11 @@ Decision: OpenPGP only for v1; S/MIME may follow later.
| 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 | Planned | | 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 | Planned | | 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 | Planned | | 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 | Planned | | 5 | Interop testing with Thunderbird and GnuPG, large attachments, multiple recipients, corrupted payloads | Automated tests done; manual interop open |
| 6 | Docs, security review, release | Planned | | 6 | Docs, security review, release | Docs and release done; independent review open |
## 6. Phase 1 implementation notes ## 6. Phase 1 implementation notes
@@ -66,7 +66,16 @@ Decision: OpenPGP only for v1; S/MIME may follow later.
- [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. Risks ## 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-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.
- 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.
- A signature from a key that differs from the one on file for the sender is flagged as a changed key.
- 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).
## 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).
+1 -1
View File
@@ -31,4 +31,4 @@ On Windows, `py -m http.server 8000` is also available on many Python installati
## Current scope ## Current scope
Mail supports multiple IMAP/SMTP accounts, switching between them, and saving message attachments. CalDAV and CardDAV servers can be added from the Calendar and Contacts views; credentials are kept in the OS-encrypted credential store, and events and contacts can sync and be edited on the server. Local contacts and events remain available without a DAV connection. Your display name is saved locally and appears in the greeting. Use the **+** beside **Folders** in the sidebar to create IMAP folders on the server; your custom folders appear in the sidebar and can be opened like any other folder. Keyboard shortcuts for compose, search, refresh, archive, delete, star, reply, forward, and message navigation can be changed in **Settings**. Attachments can be previewed (images and text) in the reader, and the **Attachments** view in the sidebar lists, searches, filters by type, previews and downloads attachments across Inbox, Sent, Archive and Trash. On desktop, **Settings → Encryption keys** creates, imports and exports passphrase-protected OpenPGP keys, stored encrypted by the operating system; sending and reading encrypted mail is planned (see [ENCRYPTION_PLAN.md](./ENCRYPTION_PLAN.md)). Run the tests with `npm test`. Mail supports multiple IMAP/SMTP accounts, switching between them, and saving message attachments. CalDAV and CardDAV servers can be added from the Calendar and Contacts views; credentials are kept in the OS-encrypted credential store, and events and contacts can sync and be edited on the server. Local contacts and events remain available without a DAV connection. Your display name is saved locally and appears in the greeting. Use the **+** beside **Folders** in the sidebar to create IMAP folders on the server; your custom folders appear in the sidebar and can be opened like any other folder. Keyboard shortcuts for compose, search, refresh, archive, delete, star, reply, forward, and message navigation can be changed in **Settings**. Attachments can be previewed (images and text) in the reader, and the **Attachments** view in the sidebar lists, searches, filters by type, previews and downloads attachments across Inbox, Sent, Archive and Trash. On desktop, **Settings → Encryption keys** creates, imports and exports passphrase-protected OpenPGP keys, stored encrypted by the operating system; you can import contacts' public keys, read encrypted or signed OpenPGP mail, and encrypt or sign outgoing messages from the compose window (see [ENCRYPTION_PLAN.md](./ENCRYPTION_PLAN.md); Android is not supported yet). Run the tests with `npm test`.
+8 -5
View File
@@ -27,11 +27,14 @@
- [ ] Add support for encrypting and decrypting mail with OpenPGP (PGP/MIME). See [ENCRYPTION_PLAN.md](./ENCRYPTION_PLAN.md). - [ ] 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. - [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. - [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.
- [ ] 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.
- [ ] 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). - [x] Phase 4 (desktop): trust levels and fingerprint verification, key-change warnings, passphrase cache timeout.
- [ ] Phase 5: interoperability testing with Thunderbird and GnuPG, large attachments, multiple recipients, corrupted payloads. - [ ] Phase 4 (Android): Android Keystore key storage, biometric unlock, and the reading/sending bridge (encryption is desktop-only until then).
- [ ] Phase 6: documentation, security review, release. - [x] Phase 5 (automated): large attachments, multiple recipients, corrupted/tampered payloads, inline PGP and PGP/MIME tests.
- [ ] Phase 5 (manual): interoperability check with Thunderbird and GnuPG.
- [x] Phase 6: documentation and release.
- [ ] Independent security review of the encryption code before relying on it.
## Appearance and settings ## Appearance and settings
+172 -16
View File
@@ -194,6 +194,7 @@ async function reconcileIdleWatchers() {
} }
const { createKeyStore } = require('./pgp-keystore.cjs'); const { createKeyStore } = require('./pgp-keystore.cjs');
const { createPgpMail, createPassphraseCache, PgpError } = require('./pgp-mail.cjs');
const pgpKeysPath = () => path.join(app.getPath('userData'), 'pgp-keys.enc'); const pgpKeysPath = () => path.join(app.getPath('userData'), 'pgp-keys.enc');
const pgpKeys = createKeyStore({ const pgpKeys = createKeyStore({
@@ -214,6 +215,9 @@ const pgpKeys = createKeyStore({
} }
}); });
const pgpCache = createPassphraseCache(async () => (await pgpKeys.getSettings()).cacheMinutes);
const pgpMail = createPgpMail({ keyStore: pgpKeys, cache: pgpCache });
async function readDavStore() { async function readDavStore() {
try { try {
const encrypted = await fs.readFile(davCredentialsPath()); const encrypted = await fs.readFile(davCredentialsPath());
@@ -559,14 +563,14 @@ async function fetchMailbox(account, folder = 'Inbox', offset = 0, limit = 20, f
async function toUiMessage(item, folder) { async function toUiMessage(item, folder) {
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 bodyText = String(parsed.text || '').replace(/\r/g, '').trim().slice(0, 20000); const pgpKind = pgpMail.detect(parsed);
const body = bodyText ? bodyText.split(/\n\s*\n/).map(part => part.trim()).filter(Boolean).slice(0, 40) : ['This message has no plain-text body.']; const encrypted = pgpKind === 'encrypted-mime' || pgpKind === 'encrypted-inline';
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: '' }
: mailContent(parsed);
const { bodyText, body, links } = content;
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();
const html = Array.isArray(parsed.html) ? parsed.html.join('') : String(parsed.html || '');
const links = [...html.matchAll(/<a\b[^>]*\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/gi)]
.map(match => (match[1] || match[2] || match[3] || '').replace(/&amp;/gi, '&').replace(/&#x2f;/gi, '/'))
.filter(Boolean)
.slice(0, 30);
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(),
@@ -574,7 +578,9 @@ async function toUiMessage(item, folder) {
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: (bodyText || parsed.subject || '').replace(/\s+/g, ' ').slice(0, 180), snippet: encrypted ? 'Encrypted message' : (bodyText || parsed.subject || '').replace(/\s+/g, ' ').slice(0, 180),
encrypted,
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(),
@@ -588,9 +594,28 @@ async function toUiMessage(item, folder) {
body, body,
links, links,
uid: Number(item.uid), uid: Number(item.uid),
attachments: (parsed.attachments || []).map(file => ({ filename: file.filename || 'attachment', size: file.size || 0 })), attachments: content.attachments,
attachment: parsed.attachments?.[0]?.filename || null, attachment: content.attachment,
size: parsed.attachments?.[0]?.size ? `${(parsed.attachments[0].size / 1048576).toFixed(1)} MB` : '' size: content.size
};
}
function mailContent(parsed) {
const bodyText = String(parsed.text || '').replace(/\r/g, '').trim().slice(0, 20000);
const body = bodyText ? bodyText.split(/\n\s*\n/).map(part => part.trim()).filter(Boolean).slice(0, 40) : ['This message has no plain-text body.'];
const html = Array.isArray(parsed.html) ? parsed.html.join('') : String(parsed.html || '');
const links = [...html.matchAll(/<a\b[^>]*\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/gi)]
.map(match => (match[1] || match[2] || match[3] || '').replace(/&amp;/gi, '&').replace(/&#x2f;/gi, '/'))
.filter(Boolean)
.slice(0, 30);
const files = (parsed.attachments || []).filter(file => !/^application\/pgp-(signature|encrypted)/i.test(file.contentType || ''));
return {
bodyText,
body,
links,
attachments: files.map(file => ({ filename: file.filename || 'attachment', size: file.size || 0 })),
attachment: files[0]?.filename || null,
size: files[0]?.size ? `${(files[0].size / 1048576).toFixed(1)} MB` : ''
}; };
} }
@@ -1158,6 +1183,18 @@ ipcMain.handle('mail:update-message', async (_event, input) => {
} }
}); });
// Encrypted messages keep their attachments inside the encrypted payload.
async function parseForAttachments(source) {
const parsed = await simpleParser(source);
const kind = pgpMail.detect(parsed);
if (kind !== 'encrypted-mime' && kind !== 'encrypted-inline') return parsed;
try {
return (await pgpMail.decrypt(parsed)).parsed;
} catch (error) {
if (error instanceof PgpError) throw new Error(error.code === 'PASSPHRASE_REQUIRED' ? 'Open the message and unlock it before using its attachments.' : error.message);
throw error;
}
}
ipcMain.handle('mail:save-attachment', async (event, input) => { ipcMain.handle('mail:save-attachment', async (event, input) => {
const account = await readAccount(); const account = await readAccount();
if (!account) throw new Error('Add a mail account before downloading attachments.'); if (!account) throw new Error('Add a mail account before downloading attachments.');
@@ -1175,7 +1212,7 @@ ipcMain.handle('mail:save-attachment', async (event, input) => {
try { try {
const item = await client.fetchOne(uid, { uid: true, source: true }, { uid: true }); const item = await client.fetchOne(uid, { uid: true, source: true }, { uid: true });
if (!item?.source) throw new Error('The message is no longer available.'); if (!item?.source) throw new Error('The message is no longer available.');
const parsed = await simpleParser(item.source); const parsed = await parseForAttachments(item.source);
const attachment = parsed.attachments?.find(file => (file.filename || 'attachment') === filename) || parsed.attachments?.[0]; const attachment = parsed.attachments?.find(file => (file.filename || 'attachment') === filename) || parsed.attachments?.[0];
if (!attachment) throw new Error('No attachment was found in this message.'); if (!attachment) throw new Error('No attachment was found in this message.');
const result = await dialog.showSaveDialog(BrowserWindow.fromWebContents(event.sender), { defaultPath: (attachment.filename || safeFilename).replace(/[\\/:*?"<>|]/g, '_') }); const result = await dialog.showSaveDialog(BrowserWindow.fromWebContents(event.sender), { defaultPath: (attachment.filename || safeFilename).replace(/[\\/:*?"<>|]/g, '_') });
@@ -1206,7 +1243,7 @@ ipcMain.handle('mail:preview-attachment', async (_event, input) => {
try { try {
const item = await client.fetchOne(uid, { uid: true, source: true }, { uid: true }); const item = await client.fetchOne(uid, { uid: true, source: true }, { uid: true });
if (!item?.source) throw new Error('The message is no longer available.'); if (!item?.source) throw new Error('The message is no longer available.');
const parsed = await simpleParser(item.source); const parsed = await parseForAttachments(item.source);
const attachment = parsed.attachments?.find(file => (file.filename || 'attachment') === filename); const attachment = parsed.attachments?.find(file => (file.filename || 'attachment') === filename);
if (!attachment) throw new Error('No attachment was found in this message.'); if (!attachment) throw new Error('No attachment was found in this message.');
const mimeType = String(attachment.contentType || '').toLowerCase().split(';')[0]; const mimeType = String(attachment.contentType || '').toLowerCase().split(';')[0];
@@ -1268,7 +1305,97 @@ ipcMain.handle('pgp:export-revocation', async (event, fingerprint, passphrase) =
const id = pgpFingerprint(fingerprint); const id = pgpFingerprint(fingerprint);
return saveKeyFile(event, `ep-mail-revocation-${id.slice(-16)}.asc`, await pgpKeys.exportRevocation(id, passphrase)); 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('pgp:delete', async (_event, fingerprint, passphrase) => {
const id = pgpFingerprint(fingerprint);
const result = await pgpKeys.remove(id, passphrase);
pgpCache.clear(id);
return result;
});
async function fetchMessageSource(account, folder, uid) {
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.');
return item.source;
} finally {
lock.release();
}
} finally {
if (client.usable) await client.logout().catch(() => {});
}
}
const pgpFailure = error => ({
failed: true,
code: error.code,
message: error.message,
fingerprint: error.details?.fingerprint || null,
email: error.details?.email || null,
missing: error.details?.missing || []
});
ipcMain.handle('pgp:decrypt-message', async (_event, input) => {
const account = await readAccount();
if (!account) throw new Error('Add a mail account before opening messages.');
const source = await fetchMessageSource(account, String(input?.folder || 'Inbox'), Number(input?.uid));
const outer = await simpleParser(source);
try {
const result = await pgpMail.decrypt(outer, { passphrase: typeof input?.passphrase === 'string' && input.passphrase ? input.passphrase : null });
const content = mailContent(result.parsed);
return {
ok: true,
body: content.body,
links: content.links,
attachments: content.attachments,
attachment: content.attachment,
size: content.size,
signatures: result.signatures,
attachedKeys: result.attachedKeys.map(key => ({ fingerprint: key.fingerprint, emails: key.emails, armoredKey: key.armoredKey }))
};
} catch (error) {
if (error instanceof PgpError) return pgpFailure(error);
throw error;
}
});
ipcMain.handle('pgp:check-send', async (_event, input) => {
const account = await readAccount();
return pgpMail.recipientStatus([input?.to, input?.cc], { sign: Boolean(input?.sign), from: account?.email || '' });
});
ipcMain.handle('pgp:contacts', () => pgpKeys.listContacts());
ipcMain.handle('pgp:add-contact', async (event, input) => {
let armoredKey = typeof input?.armoredKey === 'string' ? input.armoredKey : '';
if (!armoredKey) {
const result = await dialog.showOpenDialog(BrowserWindow.fromWebContents(event.sender), {
properties: ['openFile'], filters: [{ name: 'OpenPGP public keys', extensions: ['asc', 'gpg', 'pgp', 'key', 'txt'] }]
});
if (result.canceled || !result.filePaths[0]) return { canceled: true };
if ((await fs.stat(result.filePaths[0])).size > 200000) throw new Error('That key file is too large.');
armoredKey = await fs.readFile(result.filePaths[0], 'utf8');
}
return pgpKeys.addContact({ armoredKey, source: input?.source === 'message' ? 'message' : 'import' });
});
ipcMain.handle('pgp:set-trust', (_event, fingerprint, trust) => pgpKeys.setTrust(pgpFingerprint(fingerprint), String(trust)));
ipcMain.handle('pgp:remove-contact', (_event, fingerprint) => pgpKeys.removeContact(pgpFingerprint(fingerprint)));
ipcMain.handle('pgp:export-contact', async (event, fingerprint) => {
const id = pgpFingerprint(fingerprint);
return saveKeyFile(event, `ep-mail-contact-${id.slice(-16)}.asc`, await pgpKeys.exportContact(id));
});
ipcMain.handle('pgp:get-settings', () => pgpKeys.getSettings());
ipcMain.handle('pgp:set-settings', async (_event, input) => {
const settings = await pgpKeys.setSettings({ cacheMinutes: input?.cacheMinutes });
pgpCache.clear();
return settings;
});
ipcMain.handle('pgp:forget-passphrases', () => { pgpCache.clear(); return { cleared: true }; });
ipcMain.handle('mail:open-external', async (event, rawUrl) => { ipcMain.handle('mail:open-external', async (event, rawUrl) => {
let target; let target;
@@ -1318,15 +1445,17 @@ async function sendMailNow(account, message) {
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: sentMessageId messageId: sentMessageId
}; };
const rawMessage = message.rawBase64 ? Buffer.from(String(message.rawBase64), 'base64') : null;
try { try {
await transport.sendMail(messageOptions); if (rawMessage) await transport.sendMail({ envelope: message.envelope, raw: rawMessage });
else await transport.sendMail(messageOptions);
} finally { } finally {
transport.close(); transport.close();
} }
let savedToSent = false; let savedToSent = false;
const copy = nodemailer.createTransport({ streamTransport: true, buffer: true, newline: 'windows' }); const copy = nodemailer.createTransport({ streamTransport: true, buffer: true, newline: 'windows' });
try { try {
const rendered = await copy.sendMail(messageOptions); const rendered = rawMessage ? { message: rawMessage } : await copy.sendMail(messageOptions);
const client = imapClient(account); const client = imapClient(account);
try { try {
await client.connect(); await client.connect();
@@ -1351,7 +1480,34 @@ async function sendMailNow(account, message) {
ipcMain.handle('mail:send', async (_event, message) => { ipcMain.handle('mail:send', async (_event, message) => {
const account = await readAccount(); const account = await readAccount();
if (!account) throw new Error('Add a mail account before sending.'); if (!account) throw new Error('Add a mail account before sending.');
const pgpOptions = message?.pgp && (message.pgp.encrypt || message.pgp.sign) ? message.pgp : null;
const queuedMessage = { ...message, messageId: message?.messageId || `<${randomUUID()}@ep-mail.local>` }; const queuedMessage = { ...message, messageId: message?.messageId || `<${randomUUID()}@ep-mail.local>` };
delete queuedMessage.pgp;
if (pgpOptions) {
// Encrypt before sending or queueing so plaintext and passphrases are never stored in the outbox.
const signature = String(account.signature || '').slice(0, 5000);
const body = String(queuedMessage.text || '').slice(0, 500000);
const fromName = String(account.displayName || queuedMessage.displayName || account.email).replace(/[\r\n]+/g, ' ').trim().slice(0, 80) || account.email;
try {
const built = await pgpMail.build({
from: { name: fromName, address: account.email },
to: queuedMessage.to,
cc: queuedMessage.cc,
subject: String(queuedMessage.subject || '(no subject)').slice(0, 998),
text: signature ? `${body}${body.trim() ? '\n\n' : ''}${signature}`.slice(0, 505000) : body,
messageId: queuedMessage.messageId,
encrypt: Boolean(pgpOptions.encrypt),
sign: Boolean(pgpOptions.sign),
passphrase: typeof pgpOptions.passphrase === 'string' && pgpOptions.passphrase ? pgpOptions.passphrase : null
});
queuedMessage.rawBase64 = built.raw.toString('base64');
queuedMessage.envelope = built.envelope;
queuedMessage.text = '';
} catch (error) {
if (error instanceof PgpError) return pgpFailure(error);
throw error;
}
}
try { try {
return await sendMailNow(account, queuedMessage); return await sendMailNow(account, queuedMessage);
} catch (error) { } catch (error) {
+150 -1
View File
@@ -38,12 +38,45 @@ async function unlock(armoredPrivateKey, passphrase) {
} }
} }
const TRUST_LEVELS = ['unknown', 'trusted', 'verified'];
const DEFAULT_CACHE_MINUTES = 10;
function contactInfo(entry) {
return {
fingerprint: entry.fingerprint,
name: entry.name,
emails: entry.emails,
trust: entry.trust,
source: entry.source,
addedAt: entry.addedAt
};
}
async function readPublicOnly(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.');
const key = await openpgp.readKey({ armoredKey: armored }).catch(() => {
throw new Error('That is not a valid OpenPGP public key.');
});
await key.getPrimaryUser().catch(() => {
throw new Error('That key is expired, revoked or has no valid user ID.');
});
return key;
}
async function keyEmails(key) {
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 { keys: Array.isArray(data?.keys) ? data.keys : [] }; return {
keys: Array.isArray(data?.keys) ? data.keys : [],
contacts: Array.isArray(data?.contacts) ? data.contacts : [],
settings: data?.settings && typeof data.settings === 'object' ? data.settings : {}
};
} }
async function add(entry) { async function add(entry) {
@@ -56,6 +89,122 @@ function createKeyStore(storage) {
} }
return { return {
async listContacts() {
return (await read()).contacts.map(contactInfo);
},
async addContact({ armoredKey, source = 'import' }) {
const key = await readPublicOnly(armoredKey);
const fingerprint = key.getFingerprint().toUpperCase();
const emails = await keyEmails(key);
const data = await read();
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.');
const user = await key.getPrimaryUser();
const replaces = data.contacts
.filter(entry => entry.emails.some(email => emails.includes(email)))
.map(entry => entry.fingerprint);
const entry = {
fingerprint,
name: user.user.userID?.name || '',
emails,
trust: 'unknown',
source: ['import', 'message', 'paste'].includes(source) ? source : 'import',
addedAt: Date.now(),
publicKey: key.armor()
};
data.contacts.push(entry);
await storage.save(data);
return { contact: contactInfo(entry), keyChangedFrom: replaces };
},
async setTrust(fingerprint, trust) {
if (!TRUST_LEVELS.includes(trust)) throw new Error('Unknown trust level.');
const data = await read();
const entry = data.contacts.find(item => item.fingerprint === fingerprint);
if (!entry) throw new Error('That contact key was not found.');
entry.trust = trust;
await storage.save(data);
return contactInfo(entry);
},
async removeContact(fingerprint) {
const data = await read();
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);
await storage.save(data);
return { removed: true };
},
async exportContact(fingerprint) {
const entry = (await read()).contacts.find(item => item.fingerprint === fingerprint);
if (!entry) throw new Error('That contact key was not found.');
return entry.publicKey;
},
// Resolves public keys for recipient addresses (contacts and own keys).
async findRecipientKeys(addresses) {
const data = await read();
const pool = [
...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 }))
];
const keys = [];
const missing = [];
for (const address of addresses.map(value => String(value).trim().toLowerCase())) {
const candidates = pool
.filter(entry => entry.emails.includes(address))
.sort((a, b) => TRUST_LEVELS.indexOf(b.trust) - TRUST_LEVELS.indexOf(a.trust) || b.addedAt - a.addedAt);
let usable = null;
for (const candidate of candidates) {
try {
const key = await openpgp.readKey({ armoredKey: candidate.publicKey });
await key.getEncryptionKey();
usable = { key, fingerprint: candidate.fingerprint, trust: candidate.trust };
break;
} catch { /* expired or revoked: try the next key */ }
}
if (usable) keys.push({ address, ...usable });
else missing.push(address);
}
return { keys, missing };
},
async verificationKeys() {
const data = await read();
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 }))]) {
try {
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 */ }
}
return result;
},
async privateEntries() {
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) {
const entry = (await read()).keys.find(key => key.fingerprint === fingerprint);
if (!entry) throw new Error('That key was not found.');
return unlock(entry.privateKey, passphrase);
},
async getSettings() {
const settings = (await read()).settings;
return { cacheMinutes: Number.isFinite(settings.cacheMinutes) ? settings.cacheMinutes : DEFAULT_CACHE_MINUTES };
},
async setSettings({ cacheMinutes }) {
const minutes = Number(cacheMinutes);
if (!Number.isFinite(minutes) || minutes < 0 || minutes > 1440) throw new Error('Choose between 0 and 1440 minutes.');
const data = await read();
data.settings.cacheMinutes = Math.round(minutes);
await storage.save(data);
return { cacheMinutes: data.settings.cacheMinutes };
},
async list() { async list() {
return (await read()).keys.map(publicInfo); return (await read()).keys.map(publicInfo);
}, },
+361
View File
@@ -0,0 +1,361 @@
const openpgp = require('openpgp');
const { simpleParser } = require('mailparser');
const addressParser = require('nodemailer/lib/addressparser');
const { randomBytes } = require('node:crypto');
const ARMORED_MESSAGE = /-----BEGIN PGP MESSAGE-----[\s\S]+?-----END PGP MESSAGE-----/;
const CLEARTEXT_SIGNED = /-----BEGIN PGP SIGNED MESSAGE-----[\s\S]+?-----END PGP SIGNATURE-----/;
const MAX_ENCRYPTED_BYTES = 60 * 1048576;
class PgpError extends Error {
constructor(code, message, details = {}) {
super(message);
this.code = code;
this.details = details;
}
}
// Remembers unlocked-key passphrases in memory only, for a limited time.
function createPassphraseCache(getMinutes, now = () => Date.now()) {
const entries = new Map();
return {
async remember(fingerprint, passphrase) {
const minutes = await getMinutes();
if (!minutes) { entries.delete(fingerprint); return; }
entries.set(fingerprint, { passphrase, expires: now() + minutes * 60000 });
},
get(fingerprint) {
const entry = entries.get(fingerprint);
if (!entry) return null;
if (entry.expires <= now()) { entries.delete(fingerprint); return null; }
return entry.passphrase;
},
has(fingerprint) { return this.get(fingerprint) !== null; },
clear(fingerprint) { if (fingerprint) entries.delete(fingerprint); else entries.clear(); }
};
}
function headerValue(parsed, name) {
const value = parsed.headers?.get(name);
return value && typeof value === 'object' ? value : { value: String(value || ''), params: {} };
}
// Classifies a parsed message: encrypted/signed PGP/MIME or inline PGP.
function detect(parsed) {
const type = String(headerValue(parsed, 'content-type').value).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/signed' && protocol === 'application/pgp-signature') return 'signed-mime';
const text = String(parsed.text || '');
if (ARMORED_MESSAGE.test(text)) return 'encrypted-inline';
if (CLEARTEXT_SIGNED.test(text)) return 'signed-inline';
return null;
}
function encryptedArmor(parsed, kind) {
if (kind === 'encrypted-inline') return ARMORED_MESSAGE.exec(String(parsed.text || ''))[0];
for (const file of parsed.attachments || []) {
const content = file.content.toString('latin1');
const match = ARMORED_MESSAGE.exec(content);
if (match) return match[0];
}
throw new PgpError('CORRUPT', 'The encrypted part of this message is missing or damaged.');
}
function emailsOf(key) {
return key.getUserIDs().map(id => (/<([^>]+)>/.exec(id)?.[1] || (id.includes('@') ? id : '')).trim().toLowerCase()).filter(Boolean);
}
function fingerprintsByKeyId(verification) {
const map = new Map();
for (const item of verification) {
for (const key of item.key.getKeys()) map.set(key.getKeyID().toHex().toUpperCase(), item);
}
return map;
}
// Interprets signature results and flags a sender whose key changed.
async function describeSignatures(signatures, verification, senderEmail) {
const byKeyId = fingerprintsByKeyId(verification);
const sender = String(senderEmail || '').toLowerCase();
const results = [];
for (const signature of signatures) {
const keyId = signature.keyID.toHex().toUpperCase();
const known = byKeyId.get(keyId);
let status;
try {
await signature.verified;
status = 'valid';
} catch (error) {
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 };
if (known) {
result.email = known.emails[0] || null;
result.matchesSender = Boolean(sender) && known.emails.includes(sender);
}
if (sender && status === 'valid' && known && !known.emails.includes(sender)) result.mismatch = true;
if (sender && status !== 'unknown-key') {
const others = verification.filter(item => !item.own && item.emails.includes(sender) && item.fingerprint !== known?.fingerprint);
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;
results.push(result);
}
return results;
}
function chunkBase64(buffer) {
return buffer.toString('base64').replace(/(.{76})/g, '$1\r\n').replace(/\r\n$/, '');
}
function encodeHeader(value) {
const clean = String(value).replace(/[\r\n]+/g, ' ').trim();
if (/^[\x20-\x7e]*$/.test(clean) && clean.length <= 900) return clean;
const chars = Array.from(clean);
const words = [];
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')}?=`);
}
return words.join('\r\n ');
}
function formatAddress(entry) {
const address = String(entry.address || '').trim();
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();
return name ? `${encodeHeader(`"${name}"`)} <${address}>` : address;
}
function parseAddresses(value) {
return addressParser(String(value || '')).filter(entry => entry.address || entry.name);
}
function innerEntity(text) {
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');
}
function boundary() {
return `=_ep-${randomBytes(12).toString('hex')}`;
}
function createPgpMail({ keyStore, cache }) {
async function findDecryptionKey(message) {
const wanted = new Set(message.getEncryptionKeyIDs().map(id => id.toHex().toUpperCase()));
const entries = await keyStore.privateEntries();
const candidates = [];
for (const entry of entries) {
const publicKey = await openpgp.readKey({ armoredKey: entry.publicKey });
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.');
return candidates;
}
async function unlockAny(candidates, passphrase) {
let lastError = null;
for (const candidate of candidates) {
const secret = passphrase || cache.get(candidate.fingerprint);
if (!secret) continue;
try {
const key = await keyStore.unlockKey(candidate.fingerprint, secret);
await cache.remember(candidate.fingerprint, secret);
return key;
} catch (error) {
cache.clear(candidate.fingerprint);
lastError = error;
}
}
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.', {
fingerprint: candidates[0].fingerprint, email: candidates[0].email
});
}
return {
detect,
async decrypt(parsed, { passphrase = null } = {}) {
const kind = detect(parsed);
if (kind !== 'encrypted-mime' && kind !== 'encrypted-inline') throw new PgpError('NOT_ENCRYPTED', 'This message is not encrypted.');
const armored = encryptedArmor(parsed, kind);
if (armored.length > MAX_ENCRYPTED_BYTES) throw new PgpError('TOO_LARGE', 'This encrypted message is too large to open.');
let message;
try {
message = await openpgp.readMessage({ armoredMessage: armored });
} catch {
throw new PgpError('CORRUPT', 'The encrypted part of this message is damaged.');
}
const decryptionKey = await unlockAny(await findDecryptionKey(message), passphrase);
const verification = await keyStore.verificationKeys();
let result;
try {
result = await openpgp.decrypt({
message,
decryptionKeys: decryptionKey,
verificationKeys: verification.map(item => item.key),
format: 'binary'
});
} catch {
throw new PgpError('CORRUPT', 'The message could not be decrypted. It may be damaged or altered.');
}
const data = Buffer.from(result.data);
const sender = parsed.from?.value?.[0]?.address || '';
const signatures = await describeSignatures(result.signatures, verification, sender);
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
]));
return { parsed: inner, signatures, attachedKeys: await this.attachedKeys(inner) };
},
// Public keys attached to a message (offered to the user, never added silently).
async attachedKeys(parsed) {
const keys = [];
for (const file of parsed.attachments || []) {
const type = String(file.contentType || '').toLowerCase();
if (type !== 'application/pgp-keys' && !/\.asc$/i.test(file.filename || '')) continue;
const armored = file.content.toString('utf8');
if (!/BEGIN PGP PUBLIC KEY BLOCK/.test(armored) || armored.length > 200000) continue;
try {
const key = await openpgp.readKey({ armoredKey: armored });
keys.push({ armoredKey: armored, fingerprint: key.getFingerprint().toUpperCase(), emails: emailsOf(key) });
} catch { /* ignore unreadable attachments */ }
}
return keys.slice(0, 5);
},
// Verifies PGP/MIME (multipart/signed) and cleartext signatures on unencrypted mail.
async verifySigned(parsed, source) {
const kind = detect(parsed);
const verification = await keyStore.verificationKeys();
const sender = parsed.from?.value?.[0]?.address || '';
try {
if (kind === 'signed-inline') {
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) });
return describeSignatures(result.signatures, verification, sender);
}
if (kind !== 'signed-mime') return null;
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 }];
const signature = await openpgp.readSignature({ armoredSignature: parts.signature });
const result = await openpgp.verify({
message: await openpgp.createMessage({ binary: parts.signed }),
signature,
verificationKeys: verification.map(item => item.key)
});
return describeSignatures(result.signatures, verification, sender);
} catch {
return [{ status: 'invalid', keyId: '', fingerprint: null, trust: null, email: null, matchesSender: false, keyChanged: false }];
}
},
// Builds a complete RFC 3156 message. Returns { raw, envelope }.
async build({ from, to, cc, subject, text, messageId, date = new Date(), encrypt, sign, passphrase, signerFingerprint }) {
const toList = parseAddresses(to);
const ccList = parseAddresses(cc);
if (!toList.length) throw new Error('Add at least one recipient.');
const everyone = [...toList, ...ccList];
everyone.forEach(entry => formatAddress(entry));
let signingKey = null;
let signerEntry = null;
if (sign) {
const entries = await keyStore.privateEntries();
signerEntry = entries.find(entry => entry.fingerprint === signerFingerprint)
|| 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.');
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 });
try {
signingKey = await keyStore.unlockKey(signerEntry.fingerprint, secret);
} catch {
cache.clear(signerEntry.fingerprint);
throw new PgpError('BAD_PASSPHRASE', 'The passphrase is incorrect.', { fingerprint: signerEntry.fingerprint });
}
await cache.remember(signerEntry.fingerprint, secret);
}
const headers = [
`From: ${formatAddress(from)}`,
`To: ${toList.map(formatAddress).join(', ')}`,
...(ccList.length ? [`Cc: ${ccList.map(formatAddress).join(', ')}`] : []),
`Subject: ${encodeHeader(subject || '(no subject)')}`,
`Date: ${date.toUTCString().replace('GMT', '+0000')}`,
`Message-ID: ${String(messageId).replace(/[\r\n<>\s]/g, '').replace(/^/, '<').replace(/$/, '>')}`,
'MIME-Version: 1.0'
];
const inner = innerEntity(text);
const mark = boundary();
let body;
let contentType;
if (encrypt) {
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 });
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 armored = await openpgp.encrypt({
message: await openpgp.createMessage({ binary: inner }),
encryptionKeys: [...keys.map(item => item.key), ...ownKeys],
signingKeys: signingKey || undefined,
format: 'armored'
});
contentType = `multipart/encrypted; protocol="application/pgp-encrypted"; boundary="${mark}"`;
body = [
`--${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',
'Content-Disposition: inline; filename="encrypted.asc"', '', String(armored).replace(/\r?\n/g, '\r\n').trim(), '', `--${mark}--`, ''
].join('\r\n');
} else if (sign) {
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' });
contentType = `multipart/signed; protocol="application/pgp-signature"; micalg=pgp-sha256; boundary="${mark}"`;
const signedPart = signedBytes.toString('latin1');
body = [
`--${mark}`, signedPart, `--${mark}`, 'Content-Type: application/pgp-signature; name="signature.asc"',
'Content-Description: OpenPGP digital signature', 'Content-Disposition: attachment; filename="signature.asc"', '',
String(detached).replace(/\r?\n/g, '\r\n').trim(), '', `--${mark}--`, ''
].join('\r\n');
} else {
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');
return { raw, envelope: { from: from.address, to: everyone.map(entry => entry.address) }, signerFingerprint: signerEntry?.fingerprint || null };
},
async recipientStatus(addresses, { sign = false, from = '' } = {}) {
const list = addresses.flatMap(value => parseAddresses(value)).map(entry => entry.address).filter(Boolean);
const { keys, missing } = await keyStore.findRecipientKeys(list);
let signer = null;
if (sign) {
const entries = await keyStore.privateEntries();
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) };
}
return {
recipients: keys.map(item => ({ address: item.address, fingerprint: item.fingerprint, trust: item.trust })),
missing,
signer
};
}
};
}
// Extracts the signed part and detached signature from a multipart/signed source.
function splitSigned(source, boundaryValue) {
if (!boundaryValue) return null;
const text = Buffer.from(source).toString('latin1');
const escaped = String(boundaryValue).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const delimiter = new RegExp(`(?:^|\\r?\\n)--${escaped}(--)?[ \\t]*(?=\\r?\\n|$)`, 'g');
const marks = [...text.matchAll(delimiter)];
if (marks.length < 3) return null;
const contentAfter = mark => {
const lineEnd = text.indexOf('\n', mark.index + mark[0].length);
return lineEnd < 0 ? text.length : lineEnd + 1;
};
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 armored = /-----BEGIN PGP SIGNATURE-----[\s\S]+?-----END PGP SIGNATURE-----/.exec(signaturePart)?.[0];
if (!armored) return null;
return { signed: Buffer.from(signed, 'latin1'), signature: armored };
}
module.exports = { createPgpMail, createPassphraseCache, detect, PgpError, splitSigned };
+11 -1
View File
@@ -30,7 +30,17 @@ contextBridge.exposeInMainWorld('daybreakMail', {
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),
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),
checkSend: details => ipcRenderer.invoke('pgp:check-send', details),
contacts: () => ipcRenderer.invoke('pgp:contacts'),
addContact: details => ipcRenderer.invoke('pgp:add-contact', details),
setTrust: (fingerprint, trust) => ipcRenderer.invoke('pgp:set-trust', fingerprint, trust),
removeContact: fingerprint => ipcRenderer.invoke('pgp:remove-contact', fingerprint),
exportContact: fingerprint => ipcRenderer.invoke('pgp:export-contact', fingerprint),
getSettings: () => ipcRenderer.invoke('pgp:get-settings'),
setSettings: settings => ipcRenderer.invoke('pgp:set-settings', settings),
forgetPassphrases: () => ipcRenderer.invoke('pgp:forget-passphrases')
}, },
davList: () => ipcRenderer.invoke('dav:list'), davList: () => ipcRenderer.invoke('dav:list'),
davConnect: config => ipcRenderer.invoke('dav:connect', config), davConnect: config => ipcRenderer.invoke('dav:connect', config),
+1
View File
@@ -74,5 +74,6 @@
<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>
</body> </body>
</html> </html>
+14 -1
View File
@@ -584,13 +584,26 @@ if (window.daybreakMail) {
sendButton.disabled = true; sendButton.disabled = true;
sendButton.textContent = 'Sending…'; sendButton.textContent = 'Sending…';
try { try {
const pgp = window.pgpPrepareSend ? await window.pgpPrepareSend(recipient, $('#compose-cc').value) : null;
if (pgp === false) {
sendButton.disabled = false;
sendButton.textContent = 'Send ↗';
return;
}
const result = await window.daybreakMail.send({ const result = await window.daybreakMail.send({
to: recipient, to: recipient,
cc: $('#compose-cc').value, cc: $('#compose-cc').value,
subject: $('#compose-subject').value.trim(), subject: $('#compose-subject').value.trim(),
text: $('#compose-body').value, text: $('#compose-body').value,
displayName: connectedMailAccount.displayName || profileSettings.name displayName: connectedMailAccount.displayName || profileSettings.name,
...(pgp ? { pgp } : {})
}); });
if (result.failed) {
sendButton.disabled = false;
sendButton.textContent = 'Send ↗';
toast(result.message || 'Message could not be encrypted');
return;
}
if (result.queued) { if (result.queued) {
const draftId = $('#modal-root .compose-modal')?.dataset.draftId; const draftId = $('#modal-root .compose-modal')?.dataset.draftId;
if (draftId) await window.daybreakMail.deleteDraft(draftId); if (draftId) await window.daybreakMail.deleteDraft(draftId);
+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "ep-mail", "name": "ep-mail",
"version": "0.2.4", "version": "0.3.0",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "ep-mail", "name": "ep-mail",
"version": "0.2.4", "version": "0.3.0",
"dependencies": { "dependencies": {
"@capacitor/android": "^8.5.2", "@capacitor/android": "^8.5.2",
"@capacitor/core": "^8.5.2", "@capacitor/core": "^8.5.2",
+2 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "ep-mail", "name": "ep-mail",
"version": "0.2.4", "version": "0.3.0",
"private": true, "private": true,
"description": "Eternity Project mail client", "description": "Eternity Project mail client",
"author": "Eternity Project", "author": "Eternity Project",
@@ -45,6 +45,7 @@
"shortcuts.js", "shortcuts.js",
"attachments.js", "attachments.js",
"pgp-ui.js", "pgp-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",
+190
View File
@@ -0,0 +1,190 @@
// Reading and sending OpenPGP mail (desktop). Inert where there is no key store.
const pgpApi = () => window.daybreakMail?.pgp;
function pgpAskPassphrase(title, detail) {
return new Promise(resolve => {
const overlay = document.createElement('div');
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.querySelector('.modal-head span').textContent = title;
overlay.querySelector('.account-note').textContent = detail;
const finish = value => { overlay.remove(); resolve(value); };
overlay.querySelector('form').onsubmit = event => {
event.preventDefault();
const value = overlay.querySelector('input').value;
if (value) finish(value);
};
overlay.querySelector('[data-cancel]').onclick = () => finish(null);
overlay.addEventListener('keydown', event => { if (event.key === 'Escape') { event.stopPropagation(); finish(null); } });
document.body.append(overlay);
overlay.querySelector('input').focus();
});
}
function pgpFormatFingerprint(value) {
return String(value || '').match(/.{1,4}/g)?.join(' ') || '';
}
function pgpSignatureHtml(signatures, encrypted) {
const items = Array.isArray(signatures) ? signatures : [];
const lock = encrypted ? '🔒 Encrypted. ' : '';
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 items.map(signature => {
const trust = signature.trust === 'verified' ? 'verified key' : signature.trust === 'trusted' ? 'trusted key' : 'key not verified yet';
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.mismatch) notes.push('The signing key does not belong to the sender address.');
if (signature.status === 'valid') {
const level = signature.keyChanged || signature.mismatch ? 'bad' : signature.trust === 'unknown' ? 'warn' : 'ok';
return `<section class="pgp-status pgp-${level}" role="status"><strong>${lock}Valid signature from ${esc(signature.email || 'a known key')}</strong><span>${esc(trust)} · ${esc(pgpFormatFingerprint(signature.fingerprint))}</span>${notes.map(note => `<small>${esc(note)}</small>`).join('')}</section>`;
}
if (signature.status === 'unknown-key') {
return `<section class="pgp-status pgp-warn" role="status"><strong>${lock}Signed with an unknown key</strong><span>Key ID ${esc(signature.keyId)} is not in your contacts, so the signature cannot be checked.</span>${notes.map(note => `<small>${esc(note)}</small>`).join('')}</section>`;
}
return `<section class="pgp-status pgp-bad" role="alert"><strong>${lock}Invalid signature</strong><span>This message may have been altered or forged. Do not trust it.</span></section>`;
}).join('');
}
async function pgpAddAttachedKey(key) {
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;
try {
const result = await pgpApi().addContact({ armoredKey: key.armoredKey, source: 'message' });
toast(result.keyChangedFrom?.length ? 'Key added. Warning: you already had a different key for this address.' : 'Public key added to your contacts');
} catch (error) {
toast(error.message || 'Could not add the key');
}
}
function pgpRenderReaderState(message) {
const reader = $('#reader-pane');
const header = reader.querySelector('.reader-header');
if (!header) return;
reader.querySelectorAll('.pgp-status, .pgp-banner').forEach(node => node.remove());
let html = '';
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>`;
} else if (message.encrypted) {
html = pgpSignatureHtml(message.pgpResult?.signatures, true);
} else if (message.pgpSignatures) {
html = pgpSignatureHtml(message.pgpSignatures, false);
}
const keys = message.pgpResult?.attachedKeys || [];
header.insertAdjacentHTML('afterend', html + keys.map((key, index) => `<section class="pgp-status pgp-warn"><strong>Public key attached</strong><span>${esc(key.emails.join(', ') || 'unknown address')} · ${esc(pgpFormatFingerprint(key.fingerprint))}</span><button type="button" class="discard" data-pgp-key="${index}">Add to contacts…</button></section>`).join(''));
reader.querySelectorAll('[data-pgp-key]').forEach(button => {
button.onclick = () => pgpAddAttachedKey(keys[Number(button.dataset.pgpKey)]);
});
const unlock = $('#pgp-unlock');
if (unlock) unlock.onclick = () => pgpUnlockMessage(message, true);
}
async function pgpUnlockMessage(message, interactive) {
let passphrase = null;
for (let attempt = 0; attempt < 3; attempt += 1) {
let result;
try {
result = await pgpApi().decryptMessage({ folder: message.sourceFolder || 'Inbox', uid: message.uid, passphrase });
} catch (error) {
toast(error.message || 'Could not open this message');
return;
}
if (result.ok) {
Object.assign(message, {
body: result.body, links: result.links, attachments: result.attachments, attachment: result.attachment, size: result.size,
snippet: 'Encrypted message', pgpDecrypted: true, pgpResult: { signatures: result.signatures, attachedKeys: result.attachedKeys }
});
if (activeMessage === message.id) openMessage(message.id);
return;
}
if (result.code === 'PASSPHRASE_REQUIRED' || result.code === 'BAD_PASSPHRASE') {
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'}.`);
if (passphrase === null) return;
continue;
}
const text = $('#pgp-banner-text');
if (text) text.textContent = result.message;
else toast(result.message);
return;
}
}
if (typeof openMessage === 'function') {
const baseOpenMessage = openMessage;
openMessage = function (id) {
baseOpenMessage(id);
const message = messages.find(item => item.id === id);
if (!message || !pgpApi()) return;
pgpRenderReaderState(message);
if (message.encrypted && !message.pgpDecrypted && !message.pgpAutoTried) {
message.pgpAutoTried = true;
void pgpUnlockMessage(message, false);
}
};
}
// Compose: encrypt/sign options.
if (typeof showCompose === 'function') {
const baseShowCompose = showCompose;
showCompose = function (reply, forward = false) {
baseShowCompose(reply, forward);
const footer = $('#modal-root .compose-footer');
if (!footer || !pgpApi()) return;
const box = document.createElement('div');
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>`;
footer.prepend(box);
let touched = false;
const encrypt = $('#pgp-encrypt');
const sign = $('#pgp-sign');
if (reply?.encrypted) { encrypt.checked = true; sign.checked = true; touched = true; }
encrypt.addEventListener('change', () => { touched = true; });
let timer = null;
const refresh = async () => {
const to = $('#compose-to')?.value || '';
const cc = $('#compose-cc')?.value || '';
const hint = $('#pgp-hint');
if (!hint) return;
if (!to.trim()) { hint.textContent = ''; return; }
try {
const status = await pgpApi().checkSend({ to, cc, sign: sign.checked });
if (!$('#pgp-hint')) return;
if (status.missing.length) hint.textContent = `No public key for ${status.missing.join(', ')}`;
else {
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;
}
} catch { hint.textContent = ''; }
};
const schedule = () => { clearTimeout(timer); timer = setTimeout(refresh, 300); };
['#compose-to', '#compose-cc'].forEach(selector => $(selector)?.addEventListener('input', schedule));
sign.addEventListener('change', schedule);
schedule();
};
}
// Called by the send handler. Returns null (plain mail), false (cancelled) or send options.
window.pgpPrepareSend = async function pgpPrepareSend(to, cc) {
if (!pgpApi()) return null;
let encrypt = Boolean($('#pgp-encrypt')?.checked);
const sign = Boolean($('#pgp-sign')?.checked);
if (!encrypt && !sign) return null;
const status = await pgpApi().checkSend({ to, cc, sign });
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?`);
if (!sendPlain) return false;
encrypt = false;
if (!sign) return null;
}
let passphrase = null;
if (sign) {
if (!status.signer) { toast('Create or import an encryption key for your address before signing'); return false; }
if (!status.signer.unlocked) {
passphrase = await pgpAskPassphrase('Sign message', `Enter the passphrase for ${status.signer.email} to sign this message.`);
if (passphrase === null) return false;
}
}
return { encrypt, sign, passphrase };
};
+80 -1
View File
@@ -5,8 +5,15 @@ function openEncryptionKeys() {
const root = $('#modal-root'); const root = $('#modal-root');
const account = connectedMailAccount || {}; 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"> 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> <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">Contact public keys</h3>
<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>
<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>
<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>
<h3 class="pgp-heading">Create a key</h3> <h3 class="pgp-heading">Create a key</h3>
<label class="compose-line"><span>Name</span><input id="pgp-name" maxlength="100" value="${esc(account.displayName || '')}"></label> <label class="compose-line"><span>Name</span><input id="pgp-name" maxlength="100" value="${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>Email</span><input id="pgp-email" type="email" value="${esc(account.email || '')}"></label>
@@ -94,6 +101,78 @@ function openEncryptionKeys() {
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() {
const list = $('#pgp-contact-list');
let contacts = [];
try { contacts = await window.daybreakMail.pgp.contacts(); } catch (error) { list.textContent = error.message || 'Could not load contacts.'; return; }
list.replaceChildren();
if (!contacts.length) { list.textContent = 'No contact keys yet. Import a public key, or add one from a received message.'; return; }
contacts.forEach(contact => {
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 = contact.emails.join(', ') || contact.name || 'Public key';
const meta = document.createElement('small');
meta.textContent = `${contact.name ? contact.name + ' · ' : ''}added ${new Date(contact.addedAt).toLocaleDateString()} · from ${contact.source}`;
const fingerprint = document.createElement('small');
fingerprint.textContent = `Fingerprint: ${contact.fingerprint.match(/.{1,4}/g).join(' ')}`;
info.append(title, meta, fingerprint);
const trust = document.createElement('select');
trust.className = 'pgp-trust';
trust.setAttribute('aria-label', 'Key trust');
[['unknown', 'Not verified'], ['trusted', 'Trusted'], ['verified', 'Verified (fingerprint checked)']].forEach(([value, label]) => {
const option = document.createElement('option');
option.value = value; option.textContent = label; option.selected = contact.trust === value;
trust.append(option);
});
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(' ')}`)) {
trust.value = contact.trust;
return;
}
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.'); }
};
const actions = [
['Export', () => window.daybreakMail.pgp.exportContact(contact.fingerprint)],
['Remove', async () => {
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 renderContacts();
return { deleted: true };
}]
];
row.append(info, trust);
actions.forEach(([label, run]) => {
const button = document.createElement('button');
button.className = 'discard';
button.textContent = label;
button.onclick = async () => {
try { const result = await run(); status(result?.saved ? 'File saved.' : result?.deleted ? 'Contact key removed.' : ''); }
catch (error) { status(error.message || 'That action failed.'); }
};
row.append(button);
});
list.append(row);
});
}
$('#pgp-add-contact').onclick = async () => {
try {
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.');
await renderContacts();
} catch (error) { status(error.message || 'Could not import the key.'); }
};
window.daybreakMail.pgp.getSettings().then(settings => { $('#pgp-cache-minutes').value = settings.cacheMinutes; }).catch(() => {});
$('#pgp-save-cache').onclick = async () => {
try { const settings = await window.daybreakMail.pgp.setSettings({ cacheMinutes: Number($('#pgp-cache-minutes').value) }); status(`Passphrases are remembered for ${settings.cacheMinutes} minute(s).`); }
catch (error) { status(error.message || 'Could not save the setting.'); }
};
$('#pgp-forget').onclick = async () => { await window.daybreakMail.pgp.forgetPassphrases(); status('Remembered passphrases were cleared.'); };
void renderContacts();
void render(); void render();
} }
+1
View File
@@ -16,6 +16,7 @@ const assets = [
'shortcuts.js', 'shortcuts.js',
'attachments.js', 'attachments.js',
'pgp-ui.js', 'pgp-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',
+2 -2
View File
@@ -1,5 +1,5 @@
const CACHE='ep-mail-v6'; const CACHE='ep-mail-v7';
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']; const FILES=['./','./index.html','./styles.css','./branding.css','./app.js','./platform-bridge.js','./mail-ui.js','./productivity.js','./snooze-ui.js','./account-ui.js','./dav-ui.js','./shortcuts.js','./attachments.js','./pgp-ui.js','./pgp-mail-ui.js','./manifest.webmanifest','./icon.svg','./logo-ep-daylight.svg','./logo-ep-wasteland.svg'];
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'))))});
+7
View File
@@ -129,3 +129,10 @@ body.ep-daylight .row-check:checked{accent-color:#526a2c}
.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} .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} .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} .pgp-heading{margin:16px 0 4px;font-size:13px}.pgp-actions{display:flex;gap:8px;margin-top:8px}#open-encryption-keys{margin-top:12px}
.pgp-prompt{z-index:2000}.pgp-prompt-box{max-width:420px}
.pgp-status,.pgp-banner{display:flex;flex-direction:column;gap:2px;margin:10px 0;padding:10px 12px;border-radius:8px;border:1px solid var(--line,#c9d1c8);font-size:13px}
.pgp-status small{opacity:.85}.pgp-ok{border-color:#3d7a4f;background:rgba(61,122,79,.12)}.pgp-warn{border-color:#b8860b;background:rgba(184,134,11,.14)}.pgp-bad{border-color:#b3261e;background:rgba(179,38,30,.14)}
.pgp-banner button,.pgp-status button{align-self:flex-start;margin-top:6px}
.pgp-compose{display:flex;align-items:center;gap:12px;margin-right:auto;font-size:13px}.pgp-compose label{display:flex;align-items:center;gap:4px}.pgp-compose small{opacity:.8}
.pgp-trust{margin-left:8px}
+181
View File
@@ -0,0 +1,181 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const openpgp = require('openpgp');
const MailComposer = require('nodemailer/lib/mail-composer');
const { simpleParser } = require('mailparser');
const { createKeyStore } = require('../desktop/pgp-keystore.cjs');
const { createPgpMail, createPassphraseCache, detect } = require('../desktop/pgp-mail.cjs');
function memoryStore() {
let data = null;
return { async load() { return data && JSON.parse(JSON.stringify(data)); }, async save(value) { data = JSON.parse(JSON.stringify(value)); } };
}
async function actor(name, email, passphrase = 'correct horse') {
const keyStore = createKeyStore(memoryStore());
const cache = createPassphraseCache(async () => 10);
const mail = createPgpMail({ keyStore, cache });
const { key } = await keyStore.generate({ name, email, passphrase });
return { keyStore, cache, mail, key, email, passphrase, name };
}
async function exchange(a, b) {
await a.keyStore.addContact({ armoredKey: await b.keyStore.exportPublic(b.key.fingerprint) });
await b.keyStore.addContact({ armoredKey: await a.keyStore.exportPublic(a.key.fingerprint) });
}
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
});
test('encrypts and signs for a recipient and the sender can read the copy', async () => {
const alice = await actor('Alice', 'alice@example.com');
const bob = await actor('Bob', 'bob@example.com');
await exchange(alice, bob);
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.ok(!raw.toString('latin1').includes('Top secret'));
const parsed = await simpleParser(raw);
assert.equal(parsed.subject, 'Héllo secrèt');
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, { passphrase: 'wrong wrong' }), error => error.code === 'BAD_PASSPHRASE');
const result = await bob.mail.decrypt(parsed, { passphrase: bob.passphrase });
assert.equal(result.parsed.text.trim(), 'Top secret ✓\nline two');
assert.equal(result.signatures[0].status, 'valid');
assert.equal(result.signatures[0].matchesSender, true);
const again = await bob.mail.decrypt(await simpleParser(raw));
assert.equal(again.signatures.length, 1);
const own = await alice.mail.decrypt(parsed, { passphrase: alice.passphrase });
assert.match(own.parsed.text, /Top secret/);
});
test('refuses to encrypt without a recipient key instead of downgrading', async () => {
const alice = await actor('Alice', 'alice@example.com');
await assert.rejects(
() => alice.mail.build(sendOptions(alice, 'carol@example.com', { encrypt: true })),
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' });
assert.deepEqual(status.missing, ['carol@example.com']);
assert.equal(status.signer.email, 'alice@example.com');
});
test('encrypts to several recipients and each can decrypt', async () => {
const alice = await actor('Alice', 'alice@example.com');
const bob = await actor('Bob', 'bob@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) });
const { raw } = await alice.mail.build(sendOptions(alice, 'bob@example.com', { cc: 'carol@example.com', encrypt: true }));
const parsed = await simpleParser(raw);
for (const reader of [bob, carol]) {
const result = await reader.mail.decrypt(parsed, { passphrase: reader.passphrase });
assert.match(result.parsed.text, /Top secret/);
assert.equal(result.signatures.length, 0);
}
});
test('detects tampered and corrupted encrypted messages', async () => {
const alice = await actor('Alice', 'alice@example.com');
const bob = await actor('Bob', 'bob@example.com');
await exchange(alice, bob);
const { raw } = await alice.mail.build(sendOptions(alice, 'bob@example.com', { encrypt: true, sign: true, passphrase: alice.passphrase }));
const text = raw.toString('latin1');
const lines = text.split('\r\n');
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);
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));
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');
});
test('reports unknown signers and a changed key for a known sender', async () => {
const alice = await actor('Alice', 'alice@example.com');
const bob = await actor('Bob', 'bob@example.com');
await bob.keyStore.addContact({ armoredKey: await alice.keyStore.exportPublic(alice.key.fingerprint) });
await alice.keyStore.addContact({ armoredKey: await bob.keyStore.exportPublic(bob.key.fingerprint) });
const impostor = await actor('Alice', 'alice@example.com');
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 result = await bob.mail.decrypt(await simpleParser(raw), { passphrase: bob.passphrase });
assert.equal(result.signatures[0].status, 'unknown-key');
assert.equal(result.signatures[0].keyChanged, true);
const added = await bob.keyStore.addContact({ armoredKey: await impostor.keyStore.exportPublic(impostor.key.fingerprint) });
assert.deepEqual(added.keyChangedFrom, [alice.key.fingerprint]);
const second = await bob.mail.decrypt(await simpleParser(raw));
assert.equal(second.signatures[0].status, 'valid');
assert.equal(second.signatures[0].keyChanged, false);
});
test('signs without encrypting and verifies PGP/MIME signatures', async () => {
const alice = await actor('Alice', 'alice@example.com');
const bob = await actor('Bob', 'bob@example.com');
await bob.keyStore.addContact({ armoredKey: await alice.keyStore.exportPublic(alice.key.fingerprint) });
const { raw } = await alice.mail.build(sendOptions(alice, 'bob@example.com', { sign: true, passphrase: alice.passphrase }));
const parsed = await simpleParser(raw);
assert.equal(detect(parsed), 'signed-mime');
assert.match(parsed.text, /Top secret/);
const [signature] = await bob.mail.verifySigned(parsed, raw);
assert.equal(signature.status, 'valid');
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);
assert.equal(bad.status, 'invalid');
});
test('reads inline PGP messages and cleartext signatures', async () => {
const alice = await actor('Alice', 'alice@example.com');
const bob = await actor('Bob', 'bob@example.com');
await exchange(alice, bob);
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 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);
assert.equal(detect(parsed), 'encrypted-inline');
const result = await bob.mail.decrypt(parsed, { passphrase: bob.passphrase });
assert.equal(result.parsed.text.trim(), 'inline body');
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 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);
assert.equal(detect(signedParsed), 'signed-inline');
assert.equal((await bob.mail.verifySigned(signedParsed, signedSource))[0].status, 'valid');
});
test('decrypts large messages with attachments from other clients', async () => {
const alice = await actor('Alice', 'alice@example.com');
const bob = await actor('Bob', 'bob@example.com');
const inner = await new Promise((resolve, reject) => new MailComposer({
text: 'with attachment', attachments: [{ filename: 'big.bin', content: Buffer.alloc(8 * 1048576, 7) }]
}).compile().build((error, message) => error ? reject(error) : resolve(message)));
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 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 });
assert.equal(result.parsed.attachments[0].filename, 'big.bin');
assert.equal(result.parsed.attachments[0].content.length, 8 * 1048576);
});
test('keyring: contacts, trust levels, expired passphrase cache and settings', async () => {
const alice = await actor('Alice', 'alice@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' });
assert.equal(contact.trust, 'unknown');
assert.equal((await alice.keyStore.setTrust(contact.fingerprint, 'verified')).trust, 'verified');
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.exportPrivate(bob.key.fingerprint, bob.passphrase) }), /private key/);
await assert.rejects(() => alice.keyStore.addContact({ armoredKey: 'junk' }), /valid OpenPGP/);
assert.deepEqual(await alice.keyStore.getSettings(), { cacheMinutes: 10 });
await alice.keyStore.setSettings({ cacheMinutes: 0 });
assert.equal((await alice.keyStore.getSettings()).cacheMinutes, 0);
await alice.keyStore.removeContact(contact.fingerprint);
assert.equal((await alice.keyStore.listContacts()).length, 0);
let clock = 1000;
const cache = createPassphraseCache(async () => 1, () => clock);
await cache.remember('F', 'secret');
assert.equal(cache.get('F'), 'secret');
clock += 61000;
assert.equal(cache.get('F'), null);
});
+1
View File
@@ -74,5 +74,6 @@
<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>
</body> </body>
</html> </html>
+14 -1
View File
@@ -584,13 +584,26 @@ if (window.daybreakMail) {
sendButton.disabled = true; sendButton.disabled = true;
sendButton.textContent = 'Sending…'; sendButton.textContent = 'Sending…';
try { try {
const pgp = window.pgpPrepareSend ? await window.pgpPrepareSend(recipient, $('#compose-cc').value) : null;
if (pgp === false) {
sendButton.disabled = false;
sendButton.textContent = 'Send ↗';
return;
}
const result = await window.daybreakMail.send({ const result = await window.daybreakMail.send({
to: recipient, to: recipient,
cc: $('#compose-cc').value, cc: $('#compose-cc').value,
subject: $('#compose-subject').value.trim(), subject: $('#compose-subject').value.trim(),
text: $('#compose-body').value, text: $('#compose-body').value,
displayName: connectedMailAccount.displayName || profileSettings.name displayName: connectedMailAccount.displayName || profileSettings.name,
...(pgp ? { pgp } : {})
}); });
if (result.failed) {
sendButton.disabled = false;
sendButton.textContent = 'Send ↗';
toast(result.message || 'Message could not be encrypted');
return;
}
if (result.queued) { if (result.queued) {
const draftId = $('#modal-root .compose-modal')?.dataset.draftId; const draftId = $('#modal-root .compose-modal')?.dataset.draftId;
if (draftId) await window.daybreakMail.deleteDraft(draftId); if (draftId) await window.daybreakMail.deleteDraft(draftId);
+190
View File
@@ -0,0 +1,190 @@
// Reading and sending OpenPGP mail (desktop). Inert where there is no key store.
const pgpApi = () => window.daybreakMail?.pgp;
function pgpAskPassphrase(title, detail) {
return new Promise(resolve => {
const overlay = document.createElement('div');
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.querySelector('.modal-head span').textContent = title;
overlay.querySelector('.account-note').textContent = detail;
const finish = value => { overlay.remove(); resolve(value); };
overlay.querySelector('form').onsubmit = event => {
event.preventDefault();
const value = overlay.querySelector('input').value;
if (value) finish(value);
};
overlay.querySelector('[data-cancel]').onclick = () => finish(null);
overlay.addEventListener('keydown', event => { if (event.key === 'Escape') { event.stopPropagation(); finish(null); } });
document.body.append(overlay);
overlay.querySelector('input').focus();
});
}
function pgpFormatFingerprint(value) {
return String(value || '').match(/.{1,4}/g)?.join(' ') || '';
}
function pgpSignatureHtml(signatures, encrypted) {
const items = Array.isArray(signatures) ? signatures : [];
const lock = encrypted ? '🔒 Encrypted. ' : '';
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 items.map(signature => {
const trust = signature.trust === 'verified' ? 'verified key' : signature.trust === 'trusted' ? 'trusted key' : 'key not verified yet';
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.mismatch) notes.push('The signing key does not belong to the sender address.');
if (signature.status === 'valid') {
const level = signature.keyChanged || signature.mismatch ? 'bad' : signature.trust === 'unknown' ? 'warn' : 'ok';
return `<section class="pgp-status pgp-${level}" role="status"><strong>${lock}Valid signature from ${esc(signature.email || 'a known key')}</strong><span>${esc(trust)} · ${esc(pgpFormatFingerprint(signature.fingerprint))}</span>${notes.map(note => `<small>${esc(note)}</small>`).join('')}</section>`;
}
if (signature.status === 'unknown-key') {
return `<section class="pgp-status pgp-warn" role="status"><strong>${lock}Signed with an unknown key</strong><span>Key ID ${esc(signature.keyId)} is not in your contacts, so the signature cannot be checked.</span>${notes.map(note => `<small>${esc(note)}</small>`).join('')}</section>`;
}
return `<section class="pgp-status pgp-bad" role="alert"><strong>${lock}Invalid signature</strong><span>This message may have been altered or forged. Do not trust it.</span></section>`;
}).join('');
}
async function pgpAddAttachedKey(key) {
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;
try {
const result = await pgpApi().addContact({ armoredKey: key.armoredKey, source: 'message' });
toast(result.keyChangedFrom?.length ? 'Key added. Warning: you already had a different key for this address.' : 'Public key added to your contacts');
} catch (error) {
toast(error.message || 'Could not add the key');
}
}
function pgpRenderReaderState(message) {
const reader = $('#reader-pane');
const header = reader.querySelector('.reader-header');
if (!header) return;
reader.querySelectorAll('.pgp-status, .pgp-banner').forEach(node => node.remove());
let html = '';
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>`;
} else if (message.encrypted) {
html = pgpSignatureHtml(message.pgpResult?.signatures, true);
} else if (message.pgpSignatures) {
html = pgpSignatureHtml(message.pgpSignatures, false);
}
const keys = message.pgpResult?.attachedKeys || [];
header.insertAdjacentHTML('afterend', html + keys.map((key, index) => `<section class="pgp-status pgp-warn"><strong>Public key attached</strong><span>${esc(key.emails.join(', ') || 'unknown address')} · ${esc(pgpFormatFingerprint(key.fingerprint))}</span><button type="button" class="discard" data-pgp-key="${index}">Add to contacts…</button></section>`).join(''));
reader.querySelectorAll('[data-pgp-key]').forEach(button => {
button.onclick = () => pgpAddAttachedKey(keys[Number(button.dataset.pgpKey)]);
});
const unlock = $('#pgp-unlock');
if (unlock) unlock.onclick = () => pgpUnlockMessage(message, true);
}
async function pgpUnlockMessage(message, interactive) {
let passphrase = null;
for (let attempt = 0; attempt < 3; attempt += 1) {
let result;
try {
result = await pgpApi().decryptMessage({ folder: message.sourceFolder || 'Inbox', uid: message.uid, passphrase });
} catch (error) {
toast(error.message || 'Could not open this message');
return;
}
if (result.ok) {
Object.assign(message, {
body: result.body, links: result.links, attachments: result.attachments, attachment: result.attachment, size: result.size,
snippet: 'Encrypted message', pgpDecrypted: true, pgpResult: { signatures: result.signatures, attachedKeys: result.attachedKeys }
});
if (activeMessage === message.id) openMessage(message.id);
return;
}
if (result.code === 'PASSPHRASE_REQUIRED' || result.code === 'BAD_PASSPHRASE') {
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'}.`);
if (passphrase === null) return;
continue;
}
const text = $('#pgp-banner-text');
if (text) text.textContent = result.message;
else toast(result.message);
return;
}
}
if (typeof openMessage === 'function') {
const baseOpenMessage = openMessage;
openMessage = function (id) {
baseOpenMessage(id);
const message = messages.find(item => item.id === id);
if (!message || !pgpApi()) return;
pgpRenderReaderState(message);
if (message.encrypted && !message.pgpDecrypted && !message.pgpAutoTried) {
message.pgpAutoTried = true;
void pgpUnlockMessage(message, false);
}
};
}
// Compose: encrypt/sign options.
if (typeof showCompose === 'function') {
const baseShowCompose = showCompose;
showCompose = function (reply, forward = false) {
baseShowCompose(reply, forward);
const footer = $('#modal-root .compose-footer');
if (!footer || !pgpApi()) return;
const box = document.createElement('div');
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>`;
footer.prepend(box);
let touched = false;
const encrypt = $('#pgp-encrypt');
const sign = $('#pgp-sign');
if (reply?.encrypted) { encrypt.checked = true; sign.checked = true; touched = true; }
encrypt.addEventListener('change', () => { touched = true; });
let timer = null;
const refresh = async () => {
const to = $('#compose-to')?.value || '';
const cc = $('#compose-cc')?.value || '';
const hint = $('#pgp-hint');
if (!hint) return;
if (!to.trim()) { hint.textContent = ''; return; }
try {
const status = await pgpApi().checkSend({ to, cc, sign: sign.checked });
if (!$('#pgp-hint')) return;
if (status.missing.length) hint.textContent = `No public key for ${status.missing.join(', ')}`;
else {
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;
}
} catch { hint.textContent = ''; }
};
const schedule = () => { clearTimeout(timer); timer = setTimeout(refresh, 300); };
['#compose-to', '#compose-cc'].forEach(selector => $(selector)?.addEventListener('input', schedule));
sign.addEventListener('change', schedule);
schedule();
};
}
// Called by the send handler. Returns null (plain mail), false (cancelled) or send options.
window.pgpPrepareSend = async function pgpPrepareSend(to, cc) {
if (!pgpApi()) return null;
let encrypt = Boolean($('#pgp-encrypt')?.checked);
const sign = Boolean($('#pgp-sign')?.checked);
if (!encrypt && !sign) return null;
const status = await pgpApi().checkSend({ to, cc, sign });
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?`);
if (!sendPlain) return false;
encrypt = false;
if (!sign) return null;
}
let passphrase = null;
if (sign) {
if (!status.signer) { toast('Create or import an encryption key for your address before signing'); return false; }
if (!status.signer.unlocked) {
passphrase = await pgpAskPassphrase('Sign message', `Enter the passphrase for ${status.signer.email} to sign this message.`);
if (passphrase === null) return false;
}
}
return { encrypt, sign, passphrase };
};
+80 -1
View File
@@ -5,8 +5,15 @@ function openEncryptionKeys() {
const root = $('#modal-root'); const root = $('#modal-root');
const account = connectedMailAccount || {}; 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"> 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> <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">Contact public keys</h3>
<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>
<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>
<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>
<h3 class="pgp-heading">Create a key</h3> <h3 class="pgp-heading">Create a key</h3>
<label class="compose-line"><span>Name</span><input id="pgp-name" maxlength="100" value="${esc(account.displayName || '')}"></label> <label class="compose-line"><span>Name</span><input id="pgp-name" maxlength="100" value="${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>Email</span><input id="pgp-email" type="email" value="${esc(account.email || '')}"></label>
@@ -94,6 +101,78 @@ function openEncryptionKeys() {
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() {
const list = $('#pgp-contact-list');
let contacts = [];
try { contacts = await window.daybreakMail.pgp.contacts(); } catch (error) { list.textContent = error.message || 'Could not load contacts.'; return; }
list.replaceChildren();
if (!contacts.length) { list.textContent = 'No contact keys yet. Import a public key, or add one from a received message.'; return; }
contacts.forEach(contact => {
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 = contact.emails.join(', ') || contact.name || 'Public key';
const meta = document.createElement('small');
meta.textContent = `${contact.name ? contact.name + ' · ' : ''}added ${new Date(contact.addedAt).toLocaleDateString()} · from ${contact.source}`;
const fingerprint = document.createElement('small');
fingerprint.textContent = `Fingerprint: ${contact.fingerprint.match(/.{1,4}/g).join(' ')}`;
info.append(title, meta, fingerprint);
const trust = document.createElement('select');
trust.className = 'pgp-trust';
trust.setAttribute('aria-label', 'Key trust');
[['unknown', 'Not verified'], ['trusted', 'Trusted'], ['verified', 'Verified (fingerprint checked)']].forEach(([value, label]) => {
const option = document.createElement('option');
option.value = value; option.textContent = label; option.selected = contact.trust === value;
trust.append(option);
});
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(' ')}`)) {
trust.value = contact.trust;
return;
}
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.'); }
};
const actions = [
['Export', () => window.daybreakMail.pgp.exportContact(contact.fingerprint)],
['Remove', async () => {
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 renderContacts();
return { deleted: true };
}]
];
row.append(info, trust);
actions.forEach(([label, run]) => {
const button = document.createElement('button');
button.className = 'discard';
button.textContent = label;
button.onclick = async () => {
try { const result = await run(); status(result?.saved ? 'File saved.' : result?.deleted ? 'Contact key removed.' : ''); }
catch (error) { status(error.message || 'That action failed.'); }
};
row.append(button);
});
list.append(row);
});
}
$('#pgp-add-contact').onclick = async () => {
try {
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.');
await renderContacts();
} catch (error) { status(error.message || 'Could not import the key.'); }
};
window.daybreakMail.pgp.getSettings().then(settings => { $('#pgp-cache-minutes').value = settings.cacheMinutes; }).catch(() => {});
$('#pgp-save-cache').onclick = async () => {
try { const settings = await window.daybreakMail.pgp.setSettings({ cacheMinutes: Number($('#pgp-cache-minutes').value) }); status(`Passphrases are remembered for ${settings.cacheMinutes} minute(s).`); }
catch (error) { status(error.message || 'Could not save the setting.'); }
};
$('#pgp-forget').onclick = async () => { await window.daybreakMail.pgp.forgetPassphrases(); status('Remembered passphrases were cleared.'); };
void renderContacts();
void render(); void render();
} }
+2 -2
View File
@@ -1,5 +1,5 @@
const CACHE='ep-mail-v6'; const CACHE='ep-mail-v7';
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']; const FILES=['./','./index.html','./styles.css','./branding.css','./app.js','./platform-bridge.js','./mail-ui.js','./productivity.js','./snooze-ui.js','./account-ui.js','./dav-ui.js','./shortcuts.js','./attachments.js','./pgp-ui.js','./pgp-mail-ui.js','./manifest.webmanifest','./icon.svg','./logo-ep-daylight.svg','./logo-ep-wasteland.svg'];
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'))))});
+7
View File
@@ -129,3 +129,10 @@ body.ep-daylight .row-check:checked{accent-color:#526a2c}
.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} .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} .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} .pgp-heading{margin:16px 0 4px;font-size:13px}.pgp-actions{display:flex;gap:8px;margin-top:8px}#open-encryption-keys{margin-top:12px}
.pgp-prompt{z-index:2000}.pgp-prompt-box{max-width:420px}
.pgp-status,.pgp-banner{display:flex;flex-direction:column;gap:2px;margin:10px 0;padding:10px 12px;border-radius:8px;border:1px solid var(--line,#c9d1c8);font-size:13px}
.pgp-status small{opacity:.85}.pgp-ok{border-color:#3d7a4f;background:rgba(61,122,79,.12)}.pgp-warn{border-color:#b8860b;background:rgba(184,134,11,.14)}.pgp-bad{border-color:#b3261e;background:rgba(179,38,30,.14)}
.pgp-banner button,.pgp-status button{align-self:flex-start;margin-top:6px}
.pgp-compose{display:flex;align-items:center;gap:12px;margin-right:auto;font-size:13px}.pgp-compose label{display:flex;align-items:center;gap:4px}.pgp-compose small{opacity:.8}
.pgp-trust{margin-left:8px}