Refractoring Stage 6.2 Completed the first renderer modularization slice:
This commit is contained in:
+1
-42
@@ -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(/<!--[\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;
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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(/<!--[\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);
|
||||
@@ -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'))))});
|
||||
|
||||
Reference in New Issue
Block a user