Refractoring Stage 6.2 Completed the first renderer modularization slice:

This commit is contained in:
2026-10-16 18:30:22 +03:00
parent 297fe77fc1
commit c1961a4059
14 changed files with 216 additions and 94 deletions
+5 -3
View File
@@ -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.
+1 -42
View File
@@ -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=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[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(/<!--[\s\S]*?-->/g,'')
.replace(/<img\b[^>]*>/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 `<img${remote?` data-remote-src="${esc(remote)}"`:''}${alternative?` alt="${esc(alternative)}"`:''}>`;
})
.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=>`<div class="message ${m.unread?'unread':''} ${m.id===activeMessage?'selected':''}" data-id="${m.id}"><input class="row-check" type="checkbox" aria-label="Select message" ${selectedIds.has(m.id)?'checked':''}><div class="contact-avatar" style="background:${m.color}">${m.initials}</div><div class="message-body"><div class="sender">${esc(m.sender)}</div><div class="subject">${esc(m.subject)}</div><div class="snippet">${esc(m.snippet)}</div></div><div class="message-meta"><span class="time">${esc(m.time)}</span><button class="star ${m.star?'on':''}" aria-label="${m.star?'Unstar':'Star'}">${m.star?'★':'☆'}</button></div></div>`).join(''):`<div class="reader-empty"><div><div class="empty-icon">⌕</div><h3>No messages here</h3><p>Try another folder or search.</p></div></div>`;$$('.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;
+1
View File
@@ -65,6 +65,7 @@
<div id="modal-root"></div>
<div id="toast" class="toast" role="status" aria-live="polite"></div>
<script src="renderer-state.js"></script>
<script src="mail-content-security.js"></script>
<script src="app.js"></script>
<script src="platform-bridge.js"></script>
<script src="mail-ui.js"></script>
+75
View File
@@ -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 => ({
'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;'
})[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(/<!--[\s\S]*?-->/g, '')
.replace(/<img\b[^>]*>/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 `<img${remote ? ` data-remote-src="${escapeHtml(remote)}"` : ''}${alternative ? ` alt="${escapeHtml(alternative)}"` : ''}>`;
})
.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);
+2 -2
View File
@@ -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",
+2 -1
View File
@@ -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",
+1
View File
@@ -9,6 +9,7 @@ const assets = [
'styles.css',
'branding.css',
'renderer-state.js',
'mail-content-security.js',
'app.js',
'mail-ui.js',
'productivity.js',
+2 -2
View File
@@ -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'))))});
+22
View File
@@ -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);
});
+26
View File
@@ -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('<script src="renderer-state.js"></script>');
const contentSecurity = html.indexOf('<script src="mail-content-security.js"></script>');
const app = html.indexOf('<script src="app.js"></script>');
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}`);
}
});
+1 -42
View File
@@ -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=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[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(/<!--[\s\S]*?-->/g,'')
.replace(/<img\b[^>]*>/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 `<img${remote?` data-remote-src="${esc(remote)}"`:''}${alternative?` alt="${esc(alternative)}"`:''}>`;
})
.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=>`<div class="message ${m.unread?'unread':''} ${m.id===activeMessage?'selected':''}" data-id="${m.id}"><input class="row-check" type="checkbox" aria-label="Select message" ${selectedIds.has(m.id)?'checked':''}><div class="contact-avatar" style="background:${m.color}">${m.initials}</div><div class="message-body"><div class="sender">${esc(m.sender)}</div><div class="subject">${esc(m.subject)}</div><div class="snippet">${esc(m.snippet)}</div></div><div class="message-meta"><span class="time">${esc(m.time)}</span><button class="star ${m.star?'on':''}" aria-label="${m.star?'Unstar':'Star'}">${m.star?'★':'☆'}</button></div></div>`).join(''):`<div class="reader-empty"><div><div class="empty-icon">⌕</div><h3>No messages here</h3><p>Try another folder or search.</p></div></div>`;$$('.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;
+1
View File
@@ -65,6 +65,7 @@
<div id="modal-root"></div>
<div id="toast" class="toast" role="status" aria-live="polite"></div>
<script src="renderer-state.js"></script>
<script src="mail-content-security.js"></script>
<script src="app.js"></script>
<script src="platform-bridge.js"></script>
<script src="mail-ui.js"></script>
+75
View File
@@ -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 => ({
'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;'
})[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(/<!--[\s\S]*?-->/g, '')
.replace(/<img\b[^>]*>/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 `<img${remote ? ` data-remote-src="${escapeHtml(remote)}"` : ''}${alternative ? ` alt="${escapeHtml(alternative)}"` : ''}>`;
})
.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);
+2 -2
View File
@@ -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'))))});