diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 8041215..ce38965 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -54,11 +54,11 @@ A generation counter invalidates stale sync jobs when accounts are edited or rem The send flow is also centralized in the main process: -- the renderer calls `mail:send` -- the main process resolves the account, checks the sender settings, and applies OpenPGP encryption/signing before sending -- the message is either transmitted immediately or queued as an offline send when connectivity is unavailable +- the renderer calls the desktop `mail:send` IPC or the Android `EpMail.send` plugin with message fields and selected attachment bytes +- the native send path resolves the account, checks sender settings, builds multipart MIME, and on desktop applies OpenPGP encryption/signing to the body and attachments before sending +- the message is either transmitted immediately or queued as an offline send when connectivity is unavailable; local draft attachments are persisted with draft content -This prevents the renderer from silently bypassing critical security checks or storing plaintext in outbox data. +The renderer sends file bytes rather than local paths. OpenPGP messages are encrypted before offline queueing so the outbox contains ciphertext instead of plaintext message or attachment content. ## 3. Security boundary diff --git a/ENCRYPTION_PLAN.md b/ENCRYPTION_PLAN.md index 4f19114..19182f4 100644 --- a/ENCRYPTION_PLAN.md +++ b/ENCRYPTION_PLAN.md @@ -72,6 +72,8 @@ Decision: OpenPGP only for v1; S/MIME may follow later. - [desktop/pgp-keystore.cjs](./desktop/pgp-keystore.cjs): also stores contact public keys with trust levels (`unknown`, `trusted`, `verified`) and the passphrase-memory setting. - 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. +- Multiple outgoing attachments are included in the OpenPGP MIME payload and encrypted/signed together with the body. Android does not yet implement OpenPGP. +- Attachment selection has no app-enforced aggregate size cap; local storage capacity and mail-provider limits still apply. - A signature from a key that differs from the one on file for the sender is flagged as a changed key. - Interop: [tests/pgp-gnupg-interop.test.cjs](./tests/pgp-gnupg-interop.test.cjs) runs against a real GnuPG (skipped when it is not installed). - Tests: [tests/pgp-mail.test.cjs](./tests/pgp-mail.test.cjs) (round trips, several recipients, tampering, key changes, large attachments, inline PGP). diff --git a/README.md b/README.md index b67f0cc..a4091cd 100644 --- a/README.md +++ b/README.md @@ -33,4 +33,4 @@ On Windows, `py -m http.server 8000` is also available on many Python installati ## Current scope -Mail supports multiple IMAP/SMTP accounts, switching between them, and saving message attachments. CalDAV and CardDAV servers can be added from the Calendar and Contacts views; credentials are kept in the OS-encrypted credential store, and events and contacts can sync and be edited on the server. Local contacts and events remain available without a DAV connection. Your display name is saved locally and appears in the greeting. Use the **+** beside **Folders** in the sidebar to create IMAP folders on the server; your custom folders appear in the sidebar and can be opened like any other folder. Keyboard shortcuts for compose, search, refresh, archive, delete, star, reply, forward, and message navigation can be changed in **Settings**. Attachments can be previewed (images and text) in the reader, and the **Attachments** view in the sidebar lists, searches, filters by type, previews and downloads attachments across Inbox, Sent, Archive and Trash. On desktop, **Settings → Encryption keys** creates, imports and exports passphrase-protected OpenPGP keys stored encrypted by the operating system; you can import contact keys, enable selected key servers (all are disabled initially), search all enabled servers, and publish a key to one explicitly selected server after a native confirmation names the destination. Discovered keys remain unverified until you compare fingerprints independently. Desktop can read encrypted or signed OpenPGP mail and encrypt or sign outgoing messages (see [ENCRYPTION_PLAN.md](./ENCRYPTION_PLAN.md)); Android OpenPGP support is not available yet. Run the tests with `npm test`. +Mail supports multiple IMAP/SMTP accounts, switching between them, and saving message attachments. Compose can attach multiple files of any type; attachments are retained in local drafts and sent with the message. There is no app-enforced total-size cap, though local storage and mail providers may impose limits. Desktop encrypts and signs attachments together with the body when OpenPGP is selected. CalDAV and CardDAV servers can be added from the Calendar and Contacts views; credentials are kept in the OS-encrypted credential store, and events and contacts can sync and be edited on the server. Local contacts and events remain available without a DAV connection. Your display name is saved locally and appears in the greeting. Use the **+** beside **Folders** in the sidebar to create IMAP folders on the server; your custom folders appear in the sidebar and can be opened like any other folder. Keyboard shortcuts for compose, search, refresh, archive, delete, star, reply, forward, and message navigation can be changed in **Settings**. Attachments can be previewed (images and text) in the reader, and the **Attachments** view in the sidebar lists, searches, filters by type, previews and downloads attachments across Inbox, Sent, Archive and Trash. On desktop, **Settings → Encryption keys** creates, imports and exports passphrase-protected OpenPGP keys stored encrypted by the operating system; you can import contact keys, enable selected key servers (all are disabled initially), search all enabled servers, and publish a key to one explicitly selected server after a native confirmation names the destination. Discovered keys remain unverified until you compare fingerprints independently. Desktop can read encrypted or signed OpenPGP mail and encrypt or sign outgoing messages (see [ENCRYPTION_PLAN.md](./ENCRYPTION_PLAN.md)); Android OpenPGP support is not available yet. Run the tests with `npm test`. diff --git a/TODO.md b/TODO.md index 08ad6de..d15c316 100644 --- a/TODO.md +++ b/TODO.md @@ -68,6 +68,6 @@ - [x] Fix draft mail deletion to work like the Inbox: select multiple drafts and delete the selected drafts at once. - [x] Show created IMAP folders in the same list as Inbox and the other folders, and move the folder list and the add-folder button to the top row above Inbox. Add scrolling to the IMAP folders area. - [x] Add desktop public key server support for finding and publishing OpenPGP keys: keys.openpgp.org (VKS), keys.mailvelope.com (HKP over HTTPS), and user-defined HTTPS HKP/VKS servers. Servers are disabled until selected; lookup checks all enabled servers, and publishing requires one explicitly selected destination. Discovered keys remain unverified until fingerprint verification. -- [ ] Add the ability to attach files to outgoing mails. +- [x] Add the ability to attach multiple files to outgoing mails on desktop and Android/Web, persist them in local drafts, and include them within desktop OpenPGP protection. - [x] Fix security review findings: confirm key replacement in the main process, enforce the plaintext-send check in the main process, and handle the Linux safeStorage basic_text backend. See SECURITY_REVIEW.md. - [x] Add the ability to change the passphrase of an encryption key on desktop. diff --git a/android/app/src/main/java/studio/daybreak/mail/AndroidMailService.kt b/android/app/src/main/java/studio/daybreak/mail/AndroidMailService.kt index 829928a..ccba7a6 100644 --- a/android/app/src/main/java/studio/daybreak/mail/AndroidMailService.kt +++ b/android/app/src/main/java/studio/daybreak/mail/AndroidMailService.kt @@ -18,6 +18,8 @@ import java.util.Date import java.util.Locale import java.util.Properties import java.util.UUID +import android.util.Base64 +import javax.activation.DataHandler import javax.mail.Address import javax.mail.Authenticator import javax.mail.Flags @@ -28,6 +30,7 @@ import javax.mail.PasswordAuthentication import javax.mail.Session import javax.mail.Store import javax.mail.Transport +import javax.mail.util.ByteArrayDataSource import javax.mail.UIDFolder import javax.mail.internet.InternetAddress import javax.mail.internet.MimeBodyPart @@ -272,10 +275,37 @@ internal object AndroidMailService { message.subject = input.optString("subject", "(no subject)") val body = input.optString("text") val signature = account.optString("signature").take(5000) - message.setText( - if (signature.isBlank()) body else "$body${if (body.isBlank()) "" else "\n\n"}$signature", - "UTF-8" - ) + val fullBody = if (signature.isBlank()) body else "$body${if (body.isBlank()) "" else "\n\n"}$signature" + val attachments = input.optJSONArray("attachments") ?: JSONArray() + if (attachments.length() == 0) { + message.setText(fullBody, "UTF-8") + } else { + val multipart = MimeMultipart("mixed") + multipart.addBodyPart(MimeBodyPart().apply { setText(fullBody, "UTF-8") }) + for (index in 0 until attachments.length()) { + val file = attachments.optJSONObject(index) + ?: throw IllegalArgumentException("An attachment could not be read.") + val encoded = file.optString("contentBase64") + require(encoded.length % 4 == 0 && encoded.matches(Regex("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$"))) { + "The contents of an attachment are invalid." + } + val filename = file.optString("filename", "attachment") + .replace(Regex("[\\\\/\\r\\n\\u0000]"), "") + .take(255) + .ifBlank { "attachment" } + val contentType = file.optString("contentType", "application/octet-stream") + .lowercase(Locale.ROOT) + require(contentType.matches(Regex("^[a-z0-9!#$&^_.+-]+/[a-z0-9!#$&^_.+-]+$"))) { + "The content type for $filename is invalid." + } + val part = MimeBodyPart() + part.dataHandler = DataHandler(ByteArrayDataSource(Base64.decode(encoded, Base64.DEFAULT), contentType)) + part.fileName = MimeUtility.encodeText(filename, "UTF-8", null) + part.disposition = javax.mail.Part.ATTACHMENT + multipart.addBodyPart(part) + } + message.setContent(multipart) + } message.sentDate = Date() message.saveChanges() input.optString("messageId").takeIf(String::isNotBlank)?.let { message.setHeader("Message-ID", it) } diff --git a/android/app/src/main/java/studio/daybreak/mail/EpMailPlugin.kt b/android/app/src/main/java/studio/daybreak/mail/EpMailPlugin.kt index 546d2fa..189d1b3 100644 --- a/android/app/src/main/java/studio/daybreak/mail/EpMailPlugin.kt +++ b/android/app/src/main/java/studio/daybreak/mail/EpMailPlugin.kt @@ -331,6 +331,7 @@ class EpMailPlugin : Plugin() { .put("cc", input.optString("cc").take(4000)) .put("subject", input.optString("subject").take(998)) .put("text", input.optString("text").take(500000)) + .put("attachments", input.optJSONArray("attachments") ?: JSONArray()) .put("updatedAt", System.currentTimeMillis()) AndroidAccountVault.saveDraft(account.optString("id"), draft) call.resolve(draft.toJSObject()) diff --git a/desktop/mail-attachments.cjs b/desktop/mail-attachments.cjs new file mode 100644 index 0000000..2f3e8f6 --- /dev/null +++ b/desktop/mail-attachments.cjs @@ -0,0 +1,30 @@ +const path = require('node:path'); + +function normalizeOutgoingAttachments(value) { + if (value === undefined) return []; + if (!Array.isArray(value)) throw new Error('The attachment list is invalid.'); + return value.map(file => { + if (!file || typeof file !== 'object' || typeof file.contentBase64 !== 'string') { + throw new Error('An attachment could not be read.'); + } + const filename = path.basename(String(file.filename || 'attachment').replace(/\\/g, '/')) + .replace(/[\r\n\0]/g, '') + .slice(0, 255) || 'attachment'; + const contentType = String(file.contentType || 'application/octet-stream').trim().toLowerCase(); + if (!/^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/.test(contentType)) { + throw new Error(`The content type for ${filename} is invalid.`); + } + const encoded = file.contentBase64; + if (encoded.length % 4 !== 0 || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(encoded)) { + throw new Error(`The contents of ${filename} are invalid.`); + } + const content = Buffer.from(encoded, 'base64'); + return { filename, contentType, contentBase64: encoded, size: content.length, content }; + }); +} + +function serializeOutgoingAttachments(attachments) { + return attachments.map(({ content, ...file }) => file); +} + +module.exports = { normalizeOutgoingAttachments, serializeOutgoingAttachments }; diff --git a/desktop/main.cjs b/desktop/main.cjs index f0b54bb..600bcf8 100644 --- a/desktop/main.cjs +++ b/desktop/main.cjs @@ -9,6 +9,7 @@ const { createDAVClient } = require('tsdav'); const ICAL = require('ical.js'); const openpgp = require('openpgp'); const { createKeyServerService, listServers, MAX_CUSTOM_SERVERS, normalizeCustomServer } = require('./pgp-keyservers.cjs'); +const { normalizeOutgoingAttachments, serializeOutgoingAttachments } = require('./mail-attachments.cjs'); const credentialsPath = () => path.join(app.getPath('userData'), 'mail-account.enc'); const davCredentialsPath = () => path.join(app.getPath('userData'), 'dav-accounts.enc'); @@ -1027,6 +1028,7 @@ ipcMain.handle('mail:save-draft', async (_event, input) => { cc: String(input?.cc || '').slice(0, 4000), subject: String(input?.subject || '').slice(0, 998), text: String(input?.text || '').slice(0, 500000), + attachments: serializeOutgoingAttachments(normalizeOutgoingAttachments(input?.attachments)), updatedAt: Date.now() }; await updateAccountStore(store => { @@ -1594,6 +1596,7 @@ ipcMain.handle('mail:sync-inbox', async () => { async function sendMailNow(account, message) { const to = String(message?.to || '').trim(); if (!to) throw new Error('Add at least one recipient.'); + const attachments = normalizeOutgoingAttachments(message?.attachments); const transport = smtpTransport(account); const sentMessageId = String(message.messageId || `<${require('node:crypto').randomUUID()}@ep-mail.local>`); const fromName = String(account.displayName || message.displayName || account.email).replace(/[\r\n]+/g, ' ').trim().slice(0, 80) || account.email; @@ -1605,7 +1608,12 @@ async function sendMailNow(account, message) { cc: String(message.cc || '').trim() || undefined, subject: String(message.subject || '(no subject)').slice(0, 998), text: signature ? `${body}${body.trim() ? '\n\n' : ''}${signature}`.slice(0, 505000) : body, - messageId: sentMessageId + messageId: sentMessageId, + attachments: attachments.map(file => ({ + filename: file.filename, + contentType: file.contentType, + content: file.content + })) }; const rawMessage = message.rawBase64 ? Buffer.from(String(message.rawBase64), 'base64') : null; try { @@ -1644,6 +1652,8 @@ ipcMain.handle('mail:send', async (event, message) => { 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 attachments = normalizeOutgoingAttachments(message?.attachments); + queuedMessage.attachments = serializeOutgoingAttachments(attachments); delete queuedMessage.pgp; if (!pgpOptions?.encrypt) { const recipients = [queuedMessage.to, queuedMessage.cc].filter(Boolean); @@ -1677,11 +1687,13 @@ ipcMain.handle('mail:send', async (event, message) => { messageId: queuedMessage.messageId, encrypt: Boolean(pgpOptions.encrypt), sign: Boolean(pgpOptions.sign), - passphrase: typeof pgpOptions.passphrase === 'string' && pgpOptions.passphrase ? pgpOptions.passphrase : null + passphrase: typeof pgpOptions.passphrase === 'string' && pgpOptions.passphrase ? pgpOptions.passphrase : null, + attachments: attachments.map(({ filename, contentType, content }) => ({ filename, contentType, content })) }); queuedMessage.rawBase64 = built.raw.toString('base64'); queuedMessage.envelope = built.envelope; queuedMessage.text = ''; + queuedMessage.attachments = []; } catch (error) { if (error instanceof PgpError) return pgpFailure(error); throw error; diff --git a/desktop/pgp-mail.cjs b/desktop/pgp-mail.cjs index 7ba3dca..d75ae88 100644 --- a/desktop/pgp-mail.cjs +++ b/desktop/pgp-mail.cjs @@ -1,6 +1,7 @@ const openpgp = require('openpgp'); const { simpleParser } = require('mailparser'); const addressParser = require('nodemailer/lib/addressparser'); +const MailComposer = require('nodemailer/lib/mail-composer'); const { randomBytes } = require('node:crypto'); const ARMORED_MESSAGE = /-----BEGIN PGP MESSAGE-----[\s\S]+?-----END PGP MESSAGE-----/; @@ -131,7 +132,21 @@ function parseAddresses(value) { return addressParser(String(value || '')).filter(entry => entry.address || entry.name); } -function innerEntity(text) { +async function innerEntity(text, attachments) { + if (attachments.length) { + return new Promise((resolve, reject) => { + new MailComposer({ + text: String(text || ''), + attachments: attachments.map(file => ({ + filename: file.filename, + contentType: file.contentType, + content: file.content + })) + }).compile().build((error, message) => error + ? reject(error) + : resolve(Buffer.from(message.toString('latin1').replace(/\r?\n/g, '\r\n'), 'latin1'))); + }); + } const body = Buffer.from(String(text || ''), 'utf8'); return Buffer.from(`Content-Type: text/plain; charset=utf-8\r\nContent-Transfer-Encoding: base64\r\n\r\n${chunkBase64(body)}\r\n`, 'latin1'); } @@ -252,7 +267,7 @@ function createPgpMail({ keyStore, cache }) { }, // Builds a complete RFC 3156 message. Returns { raw, envelope }. - async build({ from, to, cc, subject, text, messageId, date = new Date(), encrypt, sign, passphrase, signerFingerprint }) { + async build({ from, to, cc, subject, text, messageId, date = new Date(), encrypt, sign, passphrase, signerFingerprint, attachments = [] }) { const toList = parseAddresses(to); const ccList = parseAddresses(cc); if (!toList.length) throw new Error('Add at least one recipient.'); @@ -284,7 +299,7 @@ function createPgpMail({ keyStore, cache }) { `Message-ID: ${String(messageId).replace(/[\r\n<>\s]/g, '').replace(/^/, '<').replace(/$/, '>')}`, 'MIME-Version: 1.0' ]; - const inner = innerEntity(text); + const inner = await innerEntity(text, attachments); const mark = boundary(); let body; let contentType; diff --git a/mail-ui.js b/mail-ui.js index 46cb5cd..ed08e02 100644 --- a/mail-ui.js +++ b/mail-ui.js @@ -398,6 +398,83 @@ function setupDraftComposer() { const modal = root.querySelector('.compose-modal'); if (!modal) return; modal.dataset.draftId = draft?.id || ''; + let attachments = Array.isArray(draft?.attachments) ? draft.attachments : []; + modal._composeAttachments = attachments; + const fields = modal.querySelector('.compose-fields'); + const attachmentRow = document.createElement('div'); + attachmentRow.className = 'compose-line'; + const attachmentLabel = document.createElement('span'); + attachmentLabel.textContent = 'Attachments'; + const attachmentControls = document.createElement('div'); + attachmentControls.className = 'compose-attachments'; + const attachmentInput = document.createElement('input'); + attachmentInput.type = 'file'; + attachmentInput.multiple = true; + attachmentInput.accept = '*/*'; + attachmentInput.hidden = true; + attachmentInput.setAttribute('aria-label', 'Choose files to attach'); + const attachButton = document.createElement('button'); + attachButton.type = 'button'; + attachButton.className = 'discard'; + attachButton.textContent = 'Attach files…'; + const attachmentList = document.createElement('div'); + attachmentList.className = 'attachment-list'; + attachmentList.setAttribute('aria-live', 'polite'); + attachmentControls.append(attachButton, attachmentInput); + attachmentRow.append(attachmentLabel, attachmentControls); + fields.append(attachmentRow, attachmentList); + attachButton.onclick = () => attachmentInput.click(); + const renderAttachments = () => { + attachmentList.replaceChildren(); + attachments.forEach((file, index) => { + const row = document.createElement('div'); + row.className = 'attachment-row'; + const name = document.createElement('strong'); + name.textContent = file.filename; + const size = document.createElement('small'); + size.textContent = `${((file.size || 0) / 1048576).toFixed(2)} MB`; + const remove = document.createElement('button'); + remove.type = 'button'; + remove.className = 'discard'; + remove.textContent = 'Remove'; + remove.setAttribute('aria-label', `Remove ${file.filename}`); + remove.onclick = () => { + attachments.splice(index, 1); + renderAttachments(); + void persist().catch(error => toast(error.message || 'Could not save the draft')); + }; + row.append(name, size, remove); + attachmentList.append(row); + }); + }; + attachmentInput.onchange = async () => { + attachButton.disabled = true; + try { + const selected = []; + for (const file of attachmentInput.files) { + const bytes = new Uint8Array(await file.arrayBuffer()); + let binary = ''; + for (let offset = 0; offset < bytes.length; offset += 0x8000) { + binary += String.fromCharCode(...bytes.subarray(offset, offset + 0x8000)); + } + selected.push({ + filename: file.name, + contentType: file.type || 'application/octet-stream', + size: file.size, + contentBase64: btoa(binary) + }); + } + attachments.push(...selected); + renderAttachments(); + await persist(); + } catch (error) { + toast(error.message || 'Could not add the selected files'); + } finally { + attachmentInput.value = ''; + attachButton.disabled = false; + } + }; + renderAttachments(); if (draft) { $('#compose-to').value = draft.to || ''; $('#compose-cc').value = draft.cc || ''; @@ -420,9 +497,10 @@ function setupDraftComposer() { to: $('#compose-to').value, cc: $('#compose-cc').value, subject: $('#compose-subject').value, - text: $('#compose-body').value + text: $('#compose-body').value, + attachments }; - if (!Object.values(values).some(value => typeof value === 'string' && value.trim())) return; + if (!Object.values(values).some(value => typeof value === 'string' && value.trim()) && !attachments.length) return; modal.dataset.draftId = values.id; const result = await window.daybreakMail.saveDraft(values); modal.dataset.draftId = result.id; @@ -668,6 +746,7 @@ if (window.daybreakMail) { cc: $('#compose-cc').value, subject: $('#compose-subject').value.trim(), text: $('#compose-body').value, + attachments: $('#modal-root .compose-modal')?._composeAttachments || [], displayName: connectedMailAccount.displayName || profileSettings.name, ...(pgp ? { pgp } : {}) }); diff --git a/tests/mail-attachments.test.cjs b/tests/mail-attachments.test.cjs new file mode 100644 index 0000000..2490bf0 --- /dev/null +++ b/tests/mail-attachments.test.cjs @@ -0,0 +1,38 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { normalizeOutgoingAttachments, serializeOutgoingAttachments } = require('../desktop/mail-attachments.cjs'); + +test('normalizes attachment metadata and round-trips bytes through serialized drafts and sends', () => { + const bytes = Buffer.from([0, 1, 2, 127, 128, 255]); + const [file] = normalizeOutgoingAttachments([{ + filename: 'folder\\report.bin', + contentType: 'APPLICATION/OCTET-STREAM', + size: 999, + contentBase64: bytes.toString('base64') + }]); + + assert.equal(file.filename, 'report.bin'); + assert.equal(file.contentType, 'application/octet-stream'); + assert.equal(file.size, bytes.length); + assert.deepEqual(file.content, bytes); + const [serialized] = serializeOutgoingAttachments([file]); + assert.equal(serialized.contentBase64, bytes.toString('base64')); + assert.equal('content' in serialized, false); +}); + +test('rejects malformed attachment data and unsafe content types', () => { + assert.throws(() => normalizeOutgoingAttachments({}), /attachment list is invalid/); + assert.throws(() => normalizeOutgoingAttachments([{ filename: 'x', contentBase64: '***=' }]), /contents.*invalid/); + assert.throws(() => normalizeOutgoingAttachments([{ + filename: 'x', + contentType: 'text/plain\r\nBcc: bad@example.com', + contentBase64: '' + }]), /content type.*invalid/); +}); + +test('uses fallback names and MIME types for empty metadata', () => { + const [file] = normalizeOutgoingAttachments([{ contentBase64: '' }]); + assert.equal(file.filename, 'attachment'); + assert.equal(file.contentType, 'application/octet-stream'); + assert.equal(file.size, 0); +}); diff --git a/tests/pgp-mail.test.cjs b/tests/pgp-mail.test.cjs index 75e34bc..39a506b 100644 --- a/tests/pgp-mail.test.cjs +++ b/tests/pgp-mail.test.cjs @@ -75,6 +75,29 @@ test('encrypts to several recipients and each can decrypt', async () => { } }); +test('encrypts and signs outgoing attachments with the message body', async () => { + const alice = await actor('Alice', 'alice@example.com'); + const bob = await actor('Bob', 'bob@example.com'); + await exchange(alice, bob); + const contents = Buffer.from([0, 1, 2, 127, 128, 255]); + const { raw } = await alice.mail.build(sendOptions(alice, 'bob@example.com', { + encrypt: true, + sign: true, + passphrase: alice.passphrase, + attachments: [{ filename: 'binary-data.bin', contentType: 'application/octet-stream', content: contents }] + })); + assert.ok(!raw.toString('latin1').includes(contents.toString('latin1'))); + + const parsed = await simpleParser(raw); + const decrypted = await bob.mail.decrypt(parsed, { passphrase: bob.passphrase }); + assert.equal(decrypted.parsed.text.trim(), 'Top secret ✓\nline two'); + assert.equal(decrypted.parsed.attachments.length, 1); + assert.equal(decrypted.parsed.attachments[0].filename, 'binary-data.bin'); + assert.equal(decrypted.parsed.attachments[0].contentType, 'application/octet-stream'); + assert.deepEqual(decrypted.parsed.attachments[0].content, contents); + assert.equal(decrypted.signatures[0].status, 'valid'); +}); + test('detects tampered and corrupted encrypted messages', async () => { const alice = await actor('Alice', 'alice@example.com'); const bob = await actor('Bob', 'bob@example.com'); @@ -112,10 +135,16 @@ test('signs without encrypting and verifies PGP/MIME signatures', async () => { const alice = await actor('Alice', 'alice@example.com'); const 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 attachment = Buffer.from('signed attachment data'); + const { raw } = await alice.mail.build(sendOptions(alice, 'bob@example.com', { + sign: true, + passphrase: alice.passphrase, + attachments: [{ filename: 'signed.txt', contentType: 'text/plain', content: attachment }] + })); const parsed = await simpleParser(raw); assert.equal(detect(parsed), 'signed-mime'); assert.match(parsed.text, /Top secret/); + assert.deepEqual(parsed.attachments[0].content, attachment); 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'); diff --git a/www/mail-ui.js b/www/mail-ui.js index 46cb5cd..ed08e02 100644 --- a/www/mail-ui.js +++ b/www/mail-ui.js @@ -398,6 +398,83 @@ function setupDraftComposer() { const modal = root.querySelector('.compose-modal'); if (!modal) return; modal.dataset.draftId = draft?.id || ''; + let attachments = Array.isArray(draft?.attachments) ? draft.attachments : []; + modal._composeAttachments = attachments; + const fields = modal.querySelector('.compose-fields'); + const attachmentRow = document.createElement('div'); + attachmentRow.className = 'compose-line'; + const attachmentLabel = document.createElement('span'); + attachmentLabel.textContent = 'Attachments'; + const attachmentControls = document.createElement('div'); + attachmentControls.className = 'compose-attachments'; + const attachmentInput = document.createElement('input'); + attachmentInput.type = 'file'; + attachmentInput.multiple = true; + attachmentInput.accept = '*/*'; + attachmentInput.hidden = true; + attachmentInput.setAttribute('aria-label', 'Choose files to attach'); + const attachButton = document.createElement('button'); + attachButton.type = 'button'; + attachButton.className = 'discard'; + attachButton.textContent = 'Attach files…'; + const attachmentList = document.createElement('div'); + attachmentList.className = 'attachment-list'; + attachmentList.setAttribute('aria-live', 'polite'); + attachmentControls.append(attachButton, attachmentInput); + attachmentRow.append(attachmentLabel, attachmentControls); + fields.append(attachmentRow, attachmentList); + attachButton.onclick = () => attachmentInput.click(); + const renderAttachments = () => { + attachmentList.replaceChildren(); + attachments.forEach((file, index) => { + const row = document.createElement('div'); + row.className = 'attachment-row'; + const name = document.createElement('strong'); + name.textContent = file.filename; + const size = document.createElement('small'); + size.textContent = `${((file.size || 0) / 1048576).toFixed(2)} MB`; + const remove = document.createElement('button'); + remove.type = 'button'; + remove.className = 'discard'; + remove.textContent = 'Remove'; + remove.setAttribute('aria-label', `Remove ${file.filename}`); + remove.onclick = () => { + attachments.splice(index, 1); + renderAttachments(); + void persist().catch(error => toast(error.message || 'Could not save the draft')); + }; + row.append(name, size, remove); + attachmentList.append(row); + }); + }; + attachmentInput.onchange = async () => { + attachButton.disabled = true; + try { + const selected = []; + for (const file of attachmentInput.files) { + const bytes = new Uint8Array(await file.arrayBuffer()); + let binary = ''; + for (let offset = 0; offset < bytes.length; offset += 0x8000) { + binary += String.fromCharCode(...bytes.subarray(offset, offset + 0x8000)); + } + selected.push({ + filename: file.name, + contentType: file.type || 'application/octet-stream', + size: file.size, + contentBase64: btoa(binary) + }); + } + attachments.push(...selected); + renderAttachments(); + await persist(); + } catch (error) { + toast(error.message || 'Could not add the selected files'); + } finally { + attachmentInput.value = ''; + attachButton.disabled = false; + } + }; + renderAttachments(); if (draft) { $('#compose-to').value = draft.to || ''; $('#compose-cc').value = draft.cc || ''; @@ -420,9 +497,10 @@ function setupDraftComposer() { to: $('#compose-to').value, cc: $('#compose-cc').value, subject: $('#compose-subject').value, - text: $('#compose-body').value + text: $('#compose-body').value, + attachments }; - if (!Object.values(values).some(value => typeof value === 'string' && value.trim())) return; + if (!Object.values(values).some(value => typeof value === 'string' && value.trim()) && !attachments.length) return; modal.dataset.draftId = values.id; const result = await window.daybreakMail.saveDraft(values); modal.dataset.draftId = result.id; @@ -668,6 +746,7 @@ if (window.daybreakMail) { cc: $('#compose-cc').value, subject: $('#compose-subject').value.trim(), text: $('#compose-body').value, + attachments: $('#modal-root .compose-modal')?._composeAttachments || [], displayName: connectedMailAccount.displayName || profileSettings.name, ...(pgp ? { pgp } : {}) });