From c1961a4059038931955e4a8cc331c7d92cb08af0 Mon Sep 17 00:00:00 2001 From: Tero Date: Fri, 16 Oct 2026 18:30:22 +0300 Subject: [PATCH] Refractoring Stage 6.2 Completed the first renderer modularization slice: --- REFACTOR_PLAN.md | 8 +-- app.js | 43 +--------------- index.html | 1 + mail-content-security.js | 75 ++++++++++++++++++++++++++++ package-lock.json | 4 +- package.json | 3 +- scripts/prepare-android-web.cjs | 1 + service-worker.js | 4 +- tests/mail-content-security.test.cjs | 22 ++++++++ tests/renderer-bootstrap.test.cjs | 26 ++++++++++ www/app.js | 43 +--------------- www/index.html | 1 + www/mail-content-security.js | 75 ++++++++++++++++++++++++++++ www/service-worker.js | 4 +- 14 files changed, 216 insertions(+), 94 deletions(-) create mode 100644 mail-content-security.js create mode 100644 tests/mail-content-security.test.cjs create mode 100644 tests/renderer-bootstrap.test.cjs create mode 100644 www/mail-content-security.js diff --git a/REFACTOR_PLAN.md b/REFACTOR_PLAN.md index 5cf2bcf..89a1bba 100644 --- a/REFACTOR_PLAN.md +++ b/REFACTOR_PLAN.md @@ -101,6 +101,7 @@ This is a gradual destination, not a requirement to move everything at once. IPC ### 6. Modularize renderer incrementally — in progress - [x] Introduce a namespaced shared renderer-state module with transitional classic-script accessors (`renderer-state.js`). +- [x] Extract mail HTML sanitization and remote-image approval checks into a dedicated renderer API (`mail-content-security.js`). - [ ] Convert mail UI to explicit feature APIs and remove legacy global dependencies. - Replace hidden globals and script-order dependencies with imports or passed dependencies. - Keep root web assets canonical and generated copies out of hand-edited workflows. @@ -127,7 +128,7 @@ This is a gradual destination, not a requirement to move everything at once. IPC - Electron Builder and the desktop Actions artifact name derive from `package.json`. - Android `versionName` derives from the same package version. Its current `versionCode` mapping is `major * 10000 + minor * 100 + patch`; keep minor and patch below 100, and revise the mapping before reaching that boundary to avoid collisions. - `scripts/build-all.ps1` uses the package version for APK naming. Before a release, bump once with `npm run bump:build`, verify the lockfile and computed Android version code, and build every target without another bump. -- Latest version check: `package.json` and both lockfile version fields are `0.4.13`; Android derives `versionName 0.4.13` and `versionCode 413`. The user confirmed the `0.4.12` artifact was built and tested; `release/` contains its Windows executable. The `0.4.13` artifact has not yet been built. +- Latest version check: `package.json` and both lockfile version fields are `0.4.14`; Android derives `versionName 0.4.14` and `versionCode 414`. `release/` currently contains Windows artifacts through `0.4.13`; no `0.4.14` artifact has been built yet. ## Progress log @@ -146,8 +147,9 @@ This is a gradual destination, not a requirement to move everything at once. IPC - Step 5 moved OpenPGP handler registration and message-source fetching into a feature module and added registration/schema coverage. - Step 5 moved DAV handler registration into a feature module and added registration/schema coverage; the full suite passes 110 tests. - Step 5 grouped mail/account handlers in `desktop/ipc/mail.cjs`; all 114 tests pass and the remaining app-version handler stays in the Electron shell. -- Added a build-version consistency check. The user bumped to `0.4.13`; package and lockfile match, and Android's derived build number is `413`. The verified release artifact remains `0.4.12`. +- Added a build-version consistency check. The user bumped to `0.4.14`; package and lockfile match, and Android's derived build number is `414`. The latest artifact observed is Windows `0.4.13`. - Step 5 grouped mail/account handlers and added a release-version consistency test; current package/lockfile/Android version alignment was checked and documented. -- Step 6 added `renderer-state.js` as the namespaced owner of shared mail/view state, retaining temporary classic-script accessors. It is included in desktop, Android-web, and service-worker asset lists and covered by state/parity tests. +- Step 6 added `renderer-state.js` as the namespaced owner of shared mail/view state and `mail-content-security.js` as a dedicated sanitizer/remote-image API. Transitional classic-script accessors remain; bootstrap order and desktop/Android/offline asset inclusion are tested. +- Step 6's first renderer slice passes 119 tests. The `0.4.14` artifact has not been built as part of this renderer change. - The current IPC/DAV validation changes pass the full suite: 108 tests. - While work continued, `package.json` and `package-lock.json` reflected a version bump to `0.4.6`; those changes were preserved. diff --git a/app.js b/app.js index e27e70a..8e05e68 100644 --- a/app.js +++ b/app.js @@ -1,48 +1,7 @@ if('serviceWorker'in navigator)window.addEventListener('load',()=>navigator.serviceWorker.register('./service-worker.js').catch(()=>{})); 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}; -} +const { safeRemoteImageUrl, sanitizeMailHtml } = window.epMailMailContentSecurity; 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; diff --git a/index.html b/index.html index fe30ad3..fdbadb9 100644 --- a/index.html +++ b/index.html @@ -65,6 +65,7 @@
+ diff --git a/mail-content-security.js b/mail-content-security.js new file mode 100644 index 0000000..fc4d16f --- /dev/null +++ b/mail-content-security.js @@ -0,0 +1,75 @@ +(function installMailContentSecurity(root) { + if (typeof module === 'object' && module.exports) { + module.exports = { createMailContentSecurity }; + return; + } + Object.defineProperty(root, 'epMailMailContentSecurity', { + value: createMailContentSecurity(root), + enumerable: false + }); + + function createMailContentSecurity(browserRoot) { + function escapeHtml(value) { + return String(value).replace(/[&<>"']/g, character => ({ + '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' + })[character]); + } + + 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 browserRoot.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 !== browserRoot.Node.ELEMENT_NODE) { + if (node.nodeType !== browserRoot.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 }; + } + + return Object.freeze({ safeRemoteImageUrl, sanitizeMailHtml }); + } +})(typeof window === 'undefined' ? globalThis : window); diff --git a/package-lock.json b/package-lock.json index 6c05ae8..c2abab6 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "ep-mail", - "version": "0.4.13", + "version": "0.4.14", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "ep-mail", - "version": "0.4.13", + "version": "0.4.14", "dependencies": { "@capacitor/android": "^8.5.2", "@capacitor/core": "^8.5.2", diff --git a/package.json b/package.json index 3568036..e6475dd 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "ep-mail", - "version": "0.4.13", + "version": "0.4.14", "private": true, "description": "Eternity Project mail client", "homepage": "https://git.eternityproject.fi/thuttu/ep-mail-client", @@ -43,6 +43,7 @@ "styles.css", "branding.css", "renderer-state.js", + "mail-content-security.js", "app.js", "mail-ui.js", "productivity.js", diff --git a/scripts/prepare-android-web.cjs b/scripts/prepare-android-web.cjs index 9c50c81..b94e1d2 100644 --- a/scripts/prepare-android-web.cjs +++ b/scripts/prepare-android-web.cjs @@ -9,6 +9,7 @@ const assets = [ 'styles.css', 'branding.css', 'renderer-state.js', + 'mail-content-security.js', 'app.js', 'mail-ui.js', 'productivity.js', diff --git a/service-worker.js b/service-worker.js index d393d53..191fd8e 100644 --- a/service-worker.js +++ b/service-worker.js @@ -1,5 +1,5 @@ -const CACHE='ep-mail-v9'; -const FILES=['./','./index.html','./styles.css','./branding.css','./renderer-state.js','./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']; +const CACHE='ep-mail-v10'; +const FILES=['./','./index.html','./styles.css','./branding.css','./renderer-state.js','./mail-content-security.js','./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)))))); 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'))))}); diff --git a/tests/mail-content-security.test.cjs b/tests/mail-content-security.test.cjs new file mode 100644 index 0000000..e4de857 --- /dev/null +++ b/tests/mail-content-security.test.cjs @@ -0,0 +1,22 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { createMailContentSecurity } = require('../mail-content-security.js'); + +test('exposes an immutable mail-content security API', () => { + const api = createMailContentSecurity({}); + assert.equal(Object.isFrozen(api), true); + assert.equal(typeof api.safeRemoteImageUrl, 'function'); + assert.equal(typeof api.sanitizeMailHtml, 'function'); +}); + +test('allows only bounded HTTPS remote image URLs without embedded credentials', () => { + const { safeRemoteImageUrl } = createMailContentSecurity({}); + assert.equal(safeRemoteImageUrl('https://images.example.test/pixel.png'), 'https://images.example.test/pixel.png'); + assert.equal(safeRemoteImageUrl('HTTPs://images.example.test/pixel.png'), 'https://images.example.test/pixel.png'); + assert.equal(safeRemoteImageUrl('http://images.example.test/pixel.png'), null); + assert.equal(safeRemoteImageUrl('data:image/png;base64,AAAA'), null); + assert.equal(safeRemoteImageUrl('https://user:pass@images.example.test/pixel.png'), null); + assert.equal(safeRemoteImageUrl(`https://images.example.test/${'x'.repeat(2050)}`), null); + assert.equal(safeRemoteImageUrl('not a URL'), null); + assert.equal(safeRemoteImageUrl(null), null); +}); diff --git a/tests/renderer-bootstrap.test.cjs b/tests/renderer-bootstrap.test.cjs new file mode 100644 index 0000000..f94eb7d --- /dev/null +++ b/tests/renderer-bootstrap.test.cjs @@ -0,0 +1,26 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); + +const root = path.resolve(__dirname, '..'); +const read = file => fs.readFileSync(path.join(root, file), 'utf8'); + +test('renderer bootstrap loads shared state and mail security before the application', () => { + const html = read('index.html'); + const state = html.indexOf(''); + const contentSecurity = html.indexOf(''); + const app = html.indexOf(''); + assert.ok(state >= 0 && contentSecurity > state && app > contentSecurity); +}); + +test('desktop, Android web generation, and offline cache include renderer support modules', () => { + const buildFiles = require(path.join(root, 'package.json')).build.files; + const androidAssets = read('scripts/prepare-android-web.cjs'); + const worker = read('service-worker.js'); + for (const file of ['renderer-state.js', 'mail-content-security.js']) { + assert.ok(buildFiles.includes(file), `Electron package is missing ${file}`); + assert.ok(androidAssets.includes(`'${file}'`), `Android web generator is missing ${file}`); + assert.ok(worker.includes(`'./${file}'`), `service worker is missing ${file}`); + } +}); diff --git a/www/app.js b/www/app.js index e27e70a..8e05e68 100644 --- a/www/app.js +++ b/www/app.js @@ -1,48 +1,7 @@ if('serviceWorker'in navigator)window.addEventListener('load',()=>navigator.serviceWorker.register('./service-worker.js').catch(()=>{})); 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}; -} +const { safeRemoteImageUrl, sanitizeMailHtml } = window.epMailMailContentSecurity; 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; diff --git a/www/index.html b/www/index.html index fe30ad3..fdbadb9 100644 --- a/www/index.html +++ b/www/index.html @@ -65,6 +65,7 @@
+ diff --git a/www/mail-content-security.js b/www/mail-content-security.js new file mode 100644 index 0000000..fc4d16f --- /dev/null +++ b/www/mail-content-security.js @@ -0,0 +1,75 @@ +(function installMailContentSecurity(root) { + if (typeof module === 'object' && module.exports) { + module.exports = { createMailContentSecurity }; + return; + } + Object.defineProperty(root, 'epMailMailContentSecurity', { + value: createMailContentSecurity(root), + enumerable: false + }); + + function createMailContentSecurity(browserRoot) { + function escapeHtml(value) { + return String(value).replace(/[&<>"']/g, character => ({ + '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' + })[character]); + } + + 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 browserRoot.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 !== browserRoot.Node.ELEMENT_NODE) { + if (node.nodeType !== browserRoot.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 }; + } + + return Object.freeze({ safeRemoteImageUrl, sanitizeMailHtml }); + } +})(typeof window === 'undefined' ? globalThis : window); diff --git a/www/service-worker.js b/www/service-worker.js index d393d53..191fd8e 100644 --- a/www/service-worker.js +++ b/www/service-worker.js @@ -1,5 +1,5 @@ -const CACHE='ep-mail-v9'; -const FILES=['./','./index.html','./styles.css','./branding.css','./renderer-state.js','./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']; +const CACHE='ep-mail-v10'; +const FILES=['./','./index.html','./styles.css','./branding.css','./renderer-state.js','./mail-content-security.js','./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)))))); 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'))))});