From 2068e3f32bbec576dd54f5806647bd3e3d5c37e9 Mon Sep 17 00:00:00 2001 From: Tero Date: Sat, 10 Oct 2026 21:53:12 +0300 Subject: [PATCH] Block remote images by default Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- ARCHITECTURE.md | 5 +- README.md | 2 +- TODO.md | 3 +- .../daybreak/mail/AndroidMailService.kt | 17 +++-- app.js | 69 ++++++++++++++++++- desktop/main.cjs | 3 + index.html | 2 +- pgp-mail-ui.js | 2 +- service-worker.js | 2 +- styles.css | 1 + www/app.js | 69 ++++++++++++++++++- www/index.html | 2 +- www/pgp-mail-ui.js | 2 +- www/service-worker.js | 2 +- www/styles.css | 1 + 15 files changed, 166 insertions(+), 16 deletions(-) diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index ce38965..7357f61 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -17,7 +17,7 @@ The browser UI is rendered from the web assets in the root and `www/` folders: - `index.html` and the shared shell files define the layout and global state. - `app.js`, `mail-ui.js`, `account-ui.js`, `dav-ui.js`, `pgp-ui.js`, and `pgp-mail-ui.js` handle page flow, compose/read views, account setup, and encryption UX. -- The renderer is intentionally thin: it requests actions and displays data, but the actual cryptographic and network work stays in the main process. +- The renderer is intentionally thin: it requests actions and displays data, while mail-protocol and cryptographic network work stays in the main process. The reader makes direct HTTPS image requests only after explicit per-message approval. ### Android client @@ -73,6 +73,7 @@ This boundary is important for encryption and safety checks: - Key-server lookup results never elevate trust; only the public key is sent during a separately confirmed publication. - Send-time downgrade checks happen in the main process rather than only in UI logic. - External links open only after a native confirmation dialog. +- Incoming HTML is sanitized in the renderer before insertion. HTTPS image URLs are kept in inert data attributes; only a per-message user action assigns image sources, and reopening the message resets that approval. HTTP images are rejected to preserve Android's cleartext-traffic protection. The CSP allows HTTPS images; scripts, frames, forms, and remote connections remain blocked. - Credentials and private keys are stored with the OS keyring, not in plain JSON files. ## 4. OpenPGP subsystem @@ -91,7 +92,7 @@ Key-server enablement is persisted in encrypted OpenPGP settings; all servers de ## 5. Data flow patterns - Account setup and edits flow from the UI into IPC, then into the encrypted main-process storage. -- Mail content is fetched by the main process and served to the renderer in a sanitized, parsed form. +- Mail content is fetched by the native mail service and passed to the renderer as plain text, bounded HTML alternatives, links, and attachment metadata. HTML is allowlist-sanitized before display; HTTPS image requests remain inert until explicitly enabled for the current message view. - Attachments, decrypted bodies, and external links are all checked before user-visible actions are allowed. - Search, folder listing, and draft operations reuse the same account model across both desktop and Android versions. diff --git a/README.md b/README.md index a4091cd..b7fe406 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ An Eternity Project mail client with **Eternity Daylight**, **Wasteland**, and E ## Desktop app -The Electron app runs in its own window. With Node.js installed, run `npm install` and then `npm start`. Open **Mail account settings** to connect an IMAP/SMTP account. Each account can have its own outgoing signature, new-mail notification toggle, periodic sync interval (2–60 minutes; IDLE remains event-driven), and mail rules. Rules match incoming Inbox messages by sender and/or subject; the first matching rule archives, moves to Inbox/Archive/Trash, applies a label, or flags the message. Sender/domain and extracted message-link checks highlight selected phishing warning signs. Message links are shown separately from the body and require explicit confirmation before opening in a browser; the app never renders remote message HTML. Settings, cached recent messages, offline drafts, and queued mail operations are stored with the encrypted account credentials. Search supports text, sender, subject, date range, attachment, and folder filters; a filtered online search scans up to the newest 5,000 messages in the selected folder. When offline, the app can read cached messages, save drafts, and queue supported message actions and sends for retry on the next successful sync. The app uses required STARTTLS for IMAP port 143 and SMTP port 587. Before preparing a new release, bump the version once with `npm run bump:build`; then build all platform targets for that same version. To package it on Windows, run `npm run dist:win`; the installer and portable `.exe` are written to `release/`. To package on Linux, run `npm install` and `npm run dist:linux` on a Linux machine; this produces AppImage and Debian packages in `release/`. +The Electron app runs in its own window. With Node.js installed, run `npm install` and then `npm start`. Open **Mail account settings** to connect an IMAP/SMTP account. Each account can have its own outgoing signature, new-mail notification toggle, periodic sync interval (2–60 minutes; IDLE remains event-driven), and mail rules. Rules match incoming Inbox messages by sender and/or subject; the first matching rule archives, moves to Inbox/Archive/Trash, applies a label, or flags the message. Sender/domain and extracted message-link checks highlight selected phishing warning signs. Message links are shown separately from the body and require explicit confirmation before opening in a browser. On desktop and Android, incoming HTML is sanitized before display; external HTTPS images stay blocked until you explicitly load them for that message. Loading remote images can disclose your network address and message-open timing to their hosts. Settings, cached recent messages, offline drafts, and queued mail operations are stored with the encrypted account credentials. Search supports text, sender, subject, date range, attachment, and folder filters; a filtered online search scans up to the newest 5,000 messages in the selected folder. When offline, the app can read cached messages, save drafts, and queue supported message actions and sends for retry on the next successful sync. The app uses required STARTTLS for IMAP port 143 and SMTP port 587. Before preparing a new release, bump the version once with `npm run bump:build`; then build all platform targets for that same version. To package it on Windows, run `npm run dist:win`; the installer and portable `.exe` are written to `release/`. To package on Linux, run `npm install` and `npm run dist:linux` on a Linux machine; this produces AppImage and Debian packages in `release/`. The `.github/workflows/desktop-build.yml` workflow builds both Windows and Linux artifacts on their native GitHub-hosted runners when manually started from the Actions tab. Snoozed messages return to their original mailbox with a reminder; desktop reminders are checked while the app is running, and Android uses its periodic background worker. diff --git a/TODO.md b/TODO.md index d15c316..e40e91a 100644 --- a/TODO.md +++ b/TODO.md @@ -4,6 +4,7 @@ - [x] Rename the program to **ep-mail** across the app UI, package metadata, desktop builds, and documentation. - [x] Replace the temporary sun/asterisk app mark with the Git and webmail logo, using the EP Daylight and EP Wasteland color variants. +- [ ] Fix the ep-mail logo not appearing in the Windows taskbar. - [x] Add Android support for the mail app. - [ ] Add macOS support: configure macOS release targets and build the app on a Mac or hosted macOS runner; sign and notarize releases for distribution. - [x] Show the app version after **ep-mail** in the window title. @@ -21,7 +22,7 @@ - [x] Add per-account rules to sort, archive, label, or flag new incoming messages by sender and/or subject. - [x] Add per-account signatures, notification preferences, and sync settings. - [x] Add the ability to create IMAP folders from the app. -- [ ] Block remote images by default and let users load them per message. +- [x] Block remote images by default and let users load them per message on desktop and Android/Web. ## Mail security 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 ccba7a6..7f4e782 100644 --- a/android/app/src/main/java/studio/daybreak/mail/AndroidMailService.kt +++ b/android/app/src/main/java/studio/daybreak/mail/AndroidMailService.kt @@ -591,9 +591,10 @@ internal object AndroidMailService { val senderEmail = sender?.address ?: "" val subject = decode(message.subject).ifBlank { "(no subject)" } val body = ArrayList() + val htmlBodies = ArrayList() val attachments = JSONArray() val links = linkedSetOf() - collectParts(message, body, attachments, links) + collectParts(message, body, htmlBodies, attachments, links) val bodyText = body.joinToString("\n\n").trim().take(8000) val snippet = (bodyText.ifBlank { subject }).replace(Regex("\\s+"), " ").take(180) val date = message.receivedDate ?: message.sentDate ?: Date() @@ -628,6 +629,7 @@ internal object AndroidMailService { .put("archived", requestedFolder == "Archive") .put("deleted", requestedFolder == "Trash") .put("sourceFolder", labelFolder) + .put("html", htmlBodies.firstOrNull()?.take(100000) ?: "") .put("body", JSONArray().apply { val paragraphs = bodyText.split(Regex("\\n\\s*\\n")).map(String::trim).filter(String::isNotEmpty).take(40) if (paragraphs.isEmpty()) put("This message has no plain-text body.") else paragraphs.forEach(::put) @@ -641,7 +643,13 @@ internal object AndroidMailService { private fun attachmentList(attachments: JSONArray): List = (0 until attachments.length()).map { attachments.getJSONObject(it) } - private fun collectParts(part: javax.mail.Part, body: MutableList, attachments: JSONArray, links: MutableSet) { + private fun collectParts( + part: javax.mail.Part, + body: MutableList, + htmlBodies: MutableList, + attachments: JSONArray, + links: MutableSet + ) { val filename = decode(part.fileName) if (filename.isNotBlank() || part.disposition.equals(javax.mail.Part.ATTACHMENT, true)) { val name = filename.ifBlank { "attachment" } @@ -654,6 +662,7 @@ internal object AndroidMailService { is String -> if (part.isMimeType("text/plain")) { body.add(content.replace("\r", "").trim()) } else if (part.isMimeType("text/html")) { + if (htmlBodies.isEmpty()) htmlBodies.add(content.take(100000)) Regex("""]*\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))""", RegexOption.IGNORE_CASE) .findAll(content) .mapNotNull { match -> (match.groups[1]?.value ?: match.groups[2]?.value ?: match.groups[3]?.value)?.replace("&", "&") } @@ -662,9 +671,9 @@ internal object AndroidMailService { if (body.isEmpty()) body.add(Html.fromHtml(content, Html.FROM_HTML_MODE_LEGACY).toString().trim()) } is Multipart -> for (index in 0 until content.count) { - collectParts(content.getBodyPart(index), body, attachments, links) + collectParts(content.getBodyPart(index), body, htmlBodies, attachments, links) } - is javax.mail.BodyPart -> collectParts(content, body, attachments, links) + is javax.mail.BodyPart -> collectParts(content, body, htmlBodies, attachments, links) } } diff --git a/app.js b/app.js index 369f5e4..c196c8c 100644 --- a/app.js +++ b/app.js @@ -4,8 +4,75 @@ const contacts=[]; let activeMessage=1,activeFolder='Inbox',activeView='mail',query='',toastTimer,selectedIds=new Set(); const $=s=>document.querySelector(s), $$=s=>[...document.querySelectorAll(s)]; function esc(x){return String(x).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]))} +function safeRemoteImageUrl(value){if(typeof value!=='string'||value.length>2048)return null;try{const url=new URL(value);return url.protocol==='https:'&&url.hostname&&!url.username&&!url.password?url.href:null}catch{return null}} +function sanitizeMailHtml(value){ + const html=String(value||'').slice(0,100000); + const inertImages=html + .replace(/<(script|style|iframe|frame|object|embed|svg|math|form|noscript|template|video|audio|source|picture|track)\b[\s\S]*?<\/\1\s*>/gi,'') + .replace(/<(?:script|style|iframe|frame|object|embed|svg|math|form|noscript|template|video|audio|source|picture|track|link|base|meta)\b[^>]*>/gi,'') + .replace(//g,'') + .replace(/]*>/gi,tag=>{ + const source=tag.match(/\bsrc\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s/>]+))/i); + const alt=tag.match(/\balt\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s/>]+))/i); + const remote=source&&(source[1]||source[2]||source[3]||'').trim(); + const alternative=alt&&(alt[1]||alt[2]||alt[3]||''); + return ``; + }) + .replace(/\s(?:src|srcset|background|poster|action|formaction|href|xlink:href|srcdoc|dynsrc|lowsrc|style)\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/gi,''); + const document=new DOMParser().parseFromString(inertImages,'text/html'); + const allowed=new Set(['a','p','div','span','br','hr','h1','h2','h3','h4','h5','h6','b','strong','i','em','u','s','del','blockquote','pre','code','ul','ol','li','table','thead','tbody','tfoot','tr','th','td','img']); + const discard=new Set(['script','style','iframe','frame','object','embed','svg','math','form','input','button','textarea','select','option','link','base','meta','video','audio','source','picture','track']); + let remoteImageCount=0; + const clean=parent=>{ + for(const node of [...parent.childNodes]){ + if(node.nodeType!==Node.ELEMENT_NODE){if(node.nodeType!==Node.TEXT_NODE)node.remove();continue} + const name=node.localName.toLowerCase(); + if(discard.has(name)){node.remove();continue} + if(!allowed.has(name)){node.replaceWith(...node.childNodes);continue} + for(const attribute of [...node.attributes]){ + const key=attribute.name.toLowerCase(); + const keep=(name==='img'&&(key==='alt'||key==='data-remote-src'))|| + (name==='td'||name==='th')&&['colspan','rowspan'].includes(key)&&/^\d{1,2}$/.test(attribute.value); + if(!keep)node.removeAttribute(attribute.name); + } + if(name==='img'){ + const url=safeRemoteImageUrl(node.getAttribute('data-remote-src')); + if(url){node.setAttribute('data-remote-src',url);remoteImageCount+=1} + else node.removeAttribute('data-remote-src'); + } + clean(node); + } + }; + clean(document.body); + return {html:document.body.innerHTML,remoteImageCount}; +} function renderList(){let rows=messages.filter(m=>{if(activeFolder==='Starred'&&!m.star)return false;if(activeFolder==='Inbox'&&m.archived)return false;if(activeFolder==='Archive'&&!m.archived)return false;if(activeFolder==='Trash'&&!m.deleted)return false;if(activeFolder==='Sent'&&!m.sent)return false;if(activeFolder==='Drafts')return false;if(activeFolder==='Snoozed')return false;if(m.deleted&&activeFolder!=='Trash')return false;return !query||`${m.sender} ${m.email} ${m.subject} ${m.snippet}`.toLowerCase().includes(query.toLowerCase())});$('#message-list').innerHTML=rows.length?rows.map(m=>`
${m.initials}
${esc(m.sender)}
${esc(m.subject)}
${esc(m.snippet)}
${esc(m.time)}
`).join(''):`
⌕

No messages here

Try another folder or search.

`;$$('.message').forEach(row=>{row.addEventListener('click',e=>{if(e.target.closest('.row-check')){const id=+row.dataset.id;selectedIds.has(id)?selectedIds.delete(id):selectedIds.add(id);return}if(e.target.closest('.star')){const m=messages.find(x=>x.id===+row.dataset.id);m.star=!m.star;renderList();return}openMessage(+row.dataset.id)});});if(!rows.length)$('#reader-pane').innerHTML=emptyReader()} -function openMessage(id){activeMessage=id;const m=messages.find(x=>x.id===id);if(!m)return;m.unread=false;renderList();$('#reader-pane').innerHTML=`
${m.tags.map((t,i)=>`${esc(t)}`).join('')}

${esc(m.subject)}

${m.initials}
${esc(m.sender)}${esc(m.email)} · to me
${esc(m.date)}
${m.body.map(p=>`

${esc(p)}

`).join('')}

${esc(m.signature||m.sender)}

${(m.attachments?.length ? m.attachments : m.attachment ? [{filename:m.attachment,size:m.size}] : []).map(file=>`
${file.filename.toLowerCase().endsWith('.pdf')?'▤':'▧'}
${esc(file.filename)}${file.size ? (typeof file.size==='string' ? esc(file.size) : `${(file.size/1048576).toFixed(1)} MB`) : 'Attachment'}
`).join('')}
`;$('#reader-archive').onclick=()=>{m.archived=true;toast('Moved to Archive');renderList();$('#reader-pane').innerHTML=emptyReader()};$('#reader-delete').onclick=()=>{m.deleted=true;toast('Moved to Trash');renderList();$('#reader-pane').innerHTML=emptyReader()};$('#reader-star').onclick=()=>{m.star=!m.star;renderList();openMessage(id)};$('#reply').onclick=()=>showCompose(m);$('#forward').onclick=()=>showCompose(m,true)} +function openMessage(id){ + activeMessage=id; + const m=messages.find(x=>x.id===id); + if(!m)return; + m.unread=false; + renderList(); + let safeHtml={html:'',remoteImageCount:0}; + if(m.html)try{safeHtml=sanitizeMailHtml(m.html)}catch(error){console.error('Could not sanitize message HTML; showing plain text instead.',error)} + const body=safeHtml.html?safeHtml.html:`${m.body.map(p=>`

${esc(p)}

`).join('')}

${esc(m.signature||m.sender)}

`; + const imageNotice=safeHtml.remoteImageCount?`

This message contains ${safeHtml.remoteImageCount} remote image${safeHtml.remoteImageCount===1?'':'s'}. Loading them can reveal your network address and that you opened this message to the image host.

`:''; + const attachments=(m.attachments?.length?m.attachments:m.attachment?[{filename:m.attachment,size:m.size}]:[]).map(file=>`
${file.filename.toLowerCase().endsWith('.pdf')?'▤':'▧'}
${esc(file.filename)}${file.size?(typeof file.size==='string'?esc(file.size):`${(file.size/1048576).toFixed(1)} MB`):'Attachment'}
`).join(''); + $('#reader-pane').innerHTML=`
${m.tags.map((t,i)=>`${esc(t)}`).join('')}

${esc(m.subject)}

${m.initials}
${esc(m.sender)}${esc(m.email)} · to me
${esc(m.date)}
${imageNotice}
${body}${attachments}
`; + $('#load-remote-images')?.addEventListener('click',()=>{ + $('#reader-pane').querySelectorAll('.reader-body img[data-remote-src]').forEach(image=>{ + const url=safeRemoteImageUrl(image.getAttribute('data-remote-src')); + image.removeAttribute('data-remote-src'); + if(url)image.src=url; + }); + $('.remote-image-notice')?.remove(); + }); + $('#reader-archive').onclick=()=>{m.archived=true;toast('Moved to Archive');renderList();$('#reader-pane').innerHTML=emptyReader()}; + $('#reader-delete').onclick=()=>{m.deleted=true;toast('Moved to Trash');renderList();$('#reader-pane').innerHTML=emptyReader()}; + $('#reader-star').onclick=()=>{m.star=!m.star;renderList();openMessage(id)}; + $('#reply').onclick=()=>showCompose(m); + $('#forward').onclick=()=>showCompose(m,true); +} function emptyReader(){return `
✉

Your inbox, at your pace

Select a message to read it here.

`} function toast(s){const el=$('#toast');el.textContent=s;el.classList.add('visible');clearTimeout(toastTimer);toastTimer=setTimeout(()=>el.classList.remove('visible'),2300)} function showCompose(reply,forward=false){const root=$('#modal-root');root.innerHTML=``;const close=()=>root.innerHTML='';$('.modal-close').onclick=close;$('#discard').onclick=close;$('.modal-overlay').addEventListener('click',e=>{if(e.target.classList.contains('modal-overlay'))close()});$('#send').onclick=()=>{const to=$('#compose-to').value.trim();if(!to){$('#compose-to').focus();toast('Add a recipient to send your message');return}const subject=$('#compose-subject').value.trim()||'(no subject)';const body=$('#compose-body').value;messages.unshift({id:Date.now(),initials:(profileSettings.name||connectedMailAccount?.email?.split('@')[0]||'Me').split(/\\s+/).map(x=>x[0]).join('').slice(0,2).toUpperCase(),color:'#dce9dd',sender:(profileSettings.name||connectedMailAccount?.email?.split('@')[0]||'Me'),email:(connectedMailAccount?.email||''),subject,snippet:body||'No message text',time:'Just now',date:'Today',unread:false,star:false,sent:true,tags:['Sent'],body:body.split('\n').filter(Boolean)});close();toast('Message sent');renderList()};$('#compose-to').focus()} diff --git a/desktop/main.cjs b/desktop/main.cjs index 600bcf8..379bdc5 100644 --- a/desktop/main.cjs +++ b/desktop/main.cjs @@ -611,6 +611,7 @@ async function toUiMessage(item, folder) { deleted: folder === 'Trash', sourceFolder: folder, body, + html: content.html, links, uid: Number(item.uid), attachments: content.attachments, @@ -631,6 +632,7 @@ function mailContent(parsed) { return { bodyText, body, + html: html.slice(0, 100000), links, attachments: files.map(file => ({ filename: file.filename || 'attachment', size: file.size || 0 })), attachment: files[0]?.filename || null, @@ -1378,6 +1380,7 @@ ipcMain.handle('pgp:decrypt-message', async (_event, input) => { return { ok: true, body: content.body, + html: content.html, links: content.links, attachments: content.attachments, attachment: content.attachment, diff --git a/index.html b/index.html index 47e4a65..c8955e1 100644 --- a/index.html +++ b/index.html @@ -5,7 +5,7 @@ - + ep-mail diff --git a/pgp-mail-ui.js b/pgp-mail-ui.js index c161bd0..3b2ce73 100644 --- a/pgp-mail-ui.js +++ b/pgp-mail-ui.js @@ -92,7 +92,7 @@ async function pgpUnlockMessage(message, interactive) { } if (result.ok) { Object.assign(message, { - body: result.body, links: result.links, attachments: result.attachments, attachment: result.attachment, size: result.size, + body: result.body, html: result.html, links: result.links, attachments: result.attachments, attachment: result.attachment, size: result.size, snippet: 'Encrypted message', pgpDecrypted: true, pgpResult: { signatures: result.signatures, attachedKeys: result.attachedKeys } }); if (activeMessage === message.id) openMessage(message.id); diff --git a/service-worker.js b/service-worker.js index b31e544..8cc21b1 100644 --- a/service-worker.js +++ b/service-worker.js @@ -1,4 +1,4 @@ -const CACHE='ep-mail-v7'; +const CACHE='ep-mail-v8'; 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('activate',event=>event.waitUntil(caches.keys().then(keys=>Promise.all(keys.filter(k=>k!==CACHE).map(k=>caches.delete(k)))))); diff --git a/styles.css b/styles.css index 674e833..b8f6385 100644 --- a/styles.css +++ b/styles.css @@ -138,5 +138,6 @@ body.ep-daylight .row-check:checked{accent-color:#526a2c} .pgp-trust{margin-left:8px} .draft-delete{margin-top:4px;font-size:15px;opacity:.55}.draft-delete:hover{opacity:1;color:#b3261e}.pgp-prompt-box{width:min(380px,92vw)} +.reader-body img{display:block;max-width:100%;height:auto;margin:12px 0;border-radius:6px}.reader-body table{max-width:100%;border-collapse:collapse}.reader-body th,.reader-body td{border:1px solid var(--line);padding:5px}.remote-image-notice{margin:14px 0 0;padding:12px;border:1px solid #d7a85c;border-radius:8px;background:#fff8e9;color:#664a23;font-size:10px;line-height:1.5}.remote-image-notice p{margin:0 0 8px}.remote-image-notice .reply-button{background:transparent;color:inherit;border-color:#d7a85c}body.ep-wasteland .remote-image-notice{background:#3a3022;color:#e6d1a8;border-color:#806b44}body.ep-daylight .remote-image-notice{background:#fff8e9;color:#664a23;border-color:#d7a85c} .sidebar{overflow-y:auto}#mail-nav{overflow-y:auto;min-height:150px;flex:0 1 auto;scrollbar-width:thin;align-content:start}#custom-folders{display:contents}.folders-head{flex:none}.sidebar>:not(#mail-nav){flex-shrink:0}.folders-head+.folder-nav{margin-top:0} diff --git a/www/app.js b/www/app.js index 369f5e4..c196c8c 100644 --- a/www/app.js +++ b/www/app.js @@ -4,8 +4,75 @@ const contacts=[]; let activeMessage=1,activeFolder='Inbox',activeView='mail',query='',toastTimer,selectedIds=new Set(); const $=s=>document.querySelector(s), $$=s=>[...document.querySelectorAll(s)]; function esc(x){return String(x).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]))} +function safeRemoteImageUrl(value){if(typeof value!=='string'||value.length>2048)return null;try{const url=new URL(value);return url.protocol==='https:'&&url.hostname&&!url.username&&!url.password?url.href:null}catch{return null}} +function sanitizeMailHtml(value){ + const html=String(value||'').slice(0,100000); + const inertImages=html + .replace(/<(script|style|iframe|frame|object|embed|svg|math|form|noscript|template|video|audio|source|picture|track)\b[\s\S]*?<\/\1\s*>/gi,'') + .replace(/<(?:script|style|iframe|frame|object|embed|svg|math|form|noscript|template|video|audio|source|picture|track|link|base|meta)\b[^>]*>/gi,'') + .replace(//g,'') + .replace(/]*>/gi,tag=>{ + const source=tag.match(/\bsrc\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s/>]+))/i); + const alt=tag.match(/\balt\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s/>]+))/i); + const remote=source&&(source[1]||source[2]||source[3]||'').trim(); + const alternative=alt&&(alt[1]||alt[2]||alt[3]||''); + return ``; + }) + .replace(/\s(?:src|srcset|background|poster|action|formaction|href|xlink:href|srcdoc|dynsrc|lowsrc|style)\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/gi,''); + const document=new DOMParser().parseFromString(inertImages,'text/html'); + const allowed=new Set(['a','p','div','span','br','hr','h1','h2','h3','h4','h5','h6','b','strong','i','em','u','s','del','blockquote','pre','code','ul','ol','li','table','thead','tbody','tfoot','tr','th','td','img']); + const discard=new Set(['script','style','iframe','frame','object','embed','svg','math','form','input','button','textarea','select','option','link','base','meta','video','audio','source','picture','track']); + let remoteImageCount=0; + const clean=parent=>{ + for(const node of [...parent.childNodes]){ + if(node.nodeType!==Node.ELEMENT_NODE){if(node.nodeType!==Node.TEXT_NODE)node.remove();continue} + const name=node.localName.toLowerCase(); + if(discard.has(name)){node.remove();continue} + if(!allowed.has(name)){node.replaceWith(...node.childNodes);continue} + for(const attribute of [...node.attributes]){ + const key=attribute.name.toLowerCase(); + const keep=(name==='img'&&(key==='alt'||key==='data-remote-src'))|| + (name==='td'||name==='th')&&['colspan','rowspan'].includes(key)&&/^\d{1,2}$/.test(attribute.value); + if(!keep)node.removeAttribute(attribute.name); + } + if(name==='img'){ + const url=safeRemoteImageUrl(node.getAttribute('data-remote-src')); + if(url){node.setAttribute('data-remote-src',url);remoteImageCount+=1} + else node.removeAttribute('data-remote-src'); + } + clean(node); + } + }; + clean(document.body); + return {html:document.body.innerHTML,remoteImageCount}; +} function renderList(){let rows=messages.filter(m=>{if(activeFolder==='Starred'&&!m.star)return false;if(activeFolder==='Inbox'&&m.archived)return false;if(activeFolder==='Archive'&&!m.archived)return false;if(activeFolder==='Trash'&&!m.deleted)return false;if(activeFolder==='Sent'&&!m.sent)return false;if(activeFolder==='Drafts')return false;if(activeFolder==='Snoozed')return false;if(m.deleted&&activeFolder!=='Trash')return false;return !query||`${m.sender} ${m.email} ${m.subject} ${m.snippet}`.toLowerCase().includes(query.toLowerCase())});$('#message-list').innerHTML=rows.length?rows.map(m=>`
${m.initials}
${esc(m.sender)}
${esc(m.subject)}
${esc(m.snippet)}
${esc(m.time)}
`).join(''):`
⌕

No messages here

Try another folder or search.

`;$$('.message').forEach(row=>{row.addEventListener('click',e=>{if(e.target.closest('.row-check')){const id=+row.dataset.id;selectedIds.has(id)?selectedIds.delete(id):selectedIds.add(id);return}if(e.target.closest('.star')){const m=messages.find(x=>x.id===+row.dataset.id);m.star=!m.star;renderList();return}openMessage(+row.dataset.id)});});if(!rows.length)$('#reader-pane').innerHTML=emptyReader()} -function openMessage(id){activeMessage=id;const m=messages.find(x=>x.id===id);if(!m)return;m.unread=false;renderList();$('#reader-pane').innerHTML=`
${m.tags.map((t,i)=>`${esc(t)}`).join('')}

${esc(m.subject)}

${m.initials}
${esc(m.sender)}${esc(m.email)} · to me
${esc(m.date)}
${m.body.map(p=>`

${esc(p)}

`).join('')}

${esc(m.signature||m.sender)}

${(m.attachments?.length ? m.attachments : m.attachment ? [{filename:m.attachment,size:m.size}] : []).map(file=>`
${file.filename.toLowerCase().endsWith('.pdf')?'▤':'▧'}
${esc(file.filename)}${file.size ? (typeof file.size==='string' ? esc(file.size) : `${(file.size/1048576).toFixed(1)} MB`) : 'Attachment'}
`).join('')}
`;$('#reader-archive').onclick=()=>{m.archived=true;toast('Moved to Archive');renderList();$('#reader-pane').innerHTML=emptyReader()};$('#reader-delete').onclick=()=>{m.deleted=true;toast('Moved to Trash');renderList();$('#reader-pane').innerHTML=emptyReader()};$('#reader-star').onclick=()=>{m.star=!m.star;renderList();openMessage(id)};$('#reply').onclick=()=>showCompose(m);$('#forward').onclick=()=>showCompose(m,true)} +function openMessage(id){ + activeMessage=id; + const m=messages.find(x=>x.id===id); + if(!m)return; + m.unread=false; + renderList(); + let safeHtml={html:'',remoteImageCount:0}; + if(m.html)try{safeHtml=sanitizeMailHtml(m.html)}catch(error){console.error('Could not sanitize message HTML; showing plain text instead.',error)} + const body=safeHtml.html?safeHtml.html:`${m.body.map(p=>`

${esc(p)}

`).join('')}

${esc(m.signature||m.sender)}

`; + const imageNotice=safeHtml.remoteImageCount?`

This message contains ${safeHtml.remoteImageCount} remote image${safeHtml.remoteImageCount===1?'':'s'}. Loading them can reveal your network address and that you opened this message to the image host.

`:''; + const attachments=(m.attachments?.length?m.attachments:m.attachment?[{filename:m.attachment,size:m.size}]:[]).map(file=>`
${file.filename.toLowerCase().endsWith('.pdf')?'▤':'▧'}
${esc(file.filename)}${file.size?(typeof file.size==='string'?esc(file.size):`${(file.size/1048576).toFixed(1)} MB`):'Attachment'}
`).join(''); + $('#reader-pane').innerHTML=`
${m.tags.map((t,i)=>`${esc(t)}`).join('')}

${esc(m.subject)}

${m.initials}
${esc(m.sender)}${esc(m.email)} · to me
${esc(m.date)}
${imageNotice}
${body}${attachments}
`; + $('#load-remote-images')?.addEventListener('click',()=>{ + $('#reader-pane').querySelectorAll('.reader-body img[data-remote-src]').forEach(image=>{ + const url=safeRemoteImageUrl(image.getAttribute('data-remote-src')); + image.removeAttribute('data-remote-src'); + if(url)image.src=url; + }); + $('.remote-image-notice')?.remove(); + }); + $('#reader-archive').onclick=()=>{m.archived=true;toast('Moved to Archive');renderList();$('#reader-pane').innerHTML=emptyReader()}; + $('#reader-delete').onclick=()=>{m.deleted=true;toast('Moved to Trash');renderList();$('#reader-pane').innerHTML=emptyReader()}; + $('#reader-star').onclick=()=>{m.star=!m.star;renderList();openMessage(id)}; + $('#reply').onclick=()=>showCompose(m); + $('#forward').onclick=()=>showCompose(m,true); +} function emptyReader(){return `
✉

Your inbox, at your pace

Select a message to read it here.

`} function toast(s){const el=$('#toast');el.textContent=s;el.classList.add('visible');clearTimeout(toastTimer);toastTimer=setTimeout(()=>el.classList.remove('visible'),2300)} function showCompose(reply,forward=false){const root=$('#modal-root');root.innerHTML=``;const close=()=>root.innerHTML='';$('.modal-close').onclick=close;$('#discard').onclick=close;$('.modal-overlay').addEventListener('click',e=>{if(e.target.classList.contains('modal-overlay'))close()});$('#send').onclick=()=>{const to=$('#compose-to').value.trim();if(!to){$('#compose-to').focus();toast('Add a recipient to send your message');return}const subject=$('#compose-subject').value.trim()||'(no subject)';const body=$('#compose-body').value;messages.unshift({id:Date.now(),initials:(profileSettings.name||connectedMailAccount?.email?.split('@')[0]||'Me').split(/\\s+/).map(x=>x[0]).join('').slice(0,2).toUpperCase(),color:'#dce9dd',sender:(profileSettings.name||connectedMailAccount?.email?.split('@')[0]||'Me'),email:(connectedMailAccount?.email||''),subject,snippet:body||'No message text',time:'Just now',date:'Today',unread:false,star:false,sent:true,tags:['Sent'],body:body.split('\n').filter(Boolean)});close();toast('Message sent');renderList()};$('#compose-to').focus()} diff --git a/www/index.html b/www/index.html index 47e4a65..c8955e1 100644 --- a/www/index.html +++ b/www/index.html @@ -5,7 +5,7 @@ - + ep-mail diff --git a/www/pgp-mail-ui.js b/www/pgp-mail-ui.js index c161bd0..3b2ce73 100644 --- a/www/pgp-mail-ui.js +++ b/www/pgp-mail-ui.js @@ -92,7 +92,7 @@ async function pgpUnlockMessage(message, interactive) { } if (result.ok) { Object.assign(message, { - body: result.body, links: result.links, attachments: result.attachments, attachment: result.attachment, size: result.size, + body: result.body, html: result.html, links: result.links, attachments: result.attachments, attachment: result.attachment, size: result.size, snippet: 'Encrypted message', pgpDecrypted: true, pgpResult: { signatures: result.signatures, attachedKeys: result.attachedKeys } }); if (activeMessage === message.id) openMessage(message.id); diff --git a/www/service-worker.js b/www/service-worker.js index b31e544..8cc21b1 100644 --- a/www/service-worker.js +++ b/www/service-worker.js @@ -1,4 +1,4 @@ -const CACHE='ep-mail-v7'; +const CACHE='ep-mail-v8'; 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('activate',event=>event.waitUntil(caches.keys().then(keys=>Promise.all(keys.filter(k=>k!==CACHE).map(k=>caches.delete(k)))))); diff --git a/www/styles.css b/www/styles.css index 674e833..b8f6385 100644 --- a/www/styles.css +++ b/www/styles.css @@ -138,5 +138,6 @@ body.ep-daylight .row-check:checked{accent-color:#526a2c} .pgp-trust{margin-left:8px} .draft-delete{margin-top:4px;font-size:15px;opacity:.55}.draft-delete:hover{opacity:1;color:#b3261e}.pgp-prompt-box{width:min(380px,92vw)} +.reader-body img{display:block;max-width:100%;height:auto;margin:12px 0;border-radius:6px}.reader-body table{max-width:100%;border-collapse:collapse}.reader-body th,.reader-body td{border:1px solid var(--line);padding:5px}.remote-image-notice{margin:14px 0 0;padding:12px;border:1px solid #d7a85c;border-radius:8px;background:#fff8e9;color:#664a23;font-size:10px;line-height:1.5}.remote-image-notice p{margin:0 0 8px}.remote-image-notice .reply-button{background:transparent;color:inherit;border-color:#d7a85c}body.ep-wasteland .remote-image-notice{background:#3a3022;color:#e6d1a8;border-color:#806b44}body.ep-daylight .remote-image-notice{background:#fff8e9;color:#664a23;border-color:#d7a85c} .sidebar{overflow-y:auto}#mail-nav{overflow-y:auto;min-height:150px;flex:0 1 auto;scrollbar-width:thin;align-content:start}#custom-folders{display:contents}.folders-head{flex:none}.sidebar>:not(#mail-nav){flex-shrink:0}.folders-head+.folder-nav{margin-top:0}