refactor: organize source web and tests by business module
This commit is contained in:
1 parent
9854d2d5c2
commit
2aed328774
113 files changed
+189
-183
No files matched your search
@@ -1,37 +0,0 @@
|
||||
'use strict';
|
||||
const {simpleParser}=require('mailparser');const sanitize=require('sanitize-html');
|
||||
const MAX_MAIL=10*1024*1024;
|
||||
const fail=message=>{throw Object.assign(new Error(message),{status:400});};
|
||||
const escape=value=>String(value??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
||||
const VARIABLES=['产品线','订单号','日期','订单列表'];
|
||||
function validateVariables(...parts){for(const part of parts)for(const token of String(part||'').matchAll(/{{([\s\S]*?)}}/g))if(!VARIABLES.includes(token[1].trim()))fail('模板含有不支持的变量,请使用:'+VARIABLES.map(x=>'{{'+x+'}}').join('、'));}
|
||||
function cleanHtml(html,attachments=[]){
|
||||
let expandedBytes=Buffer.byteLength(html||'');
|
||||
const inline=new Map(attachments.filter(a=>a.cid && /^image\/(png|jpeg|gif|webp)$/.test(a.contentType)).map(a=>[a.cid,'data:'+a.contentType+';base64,'+a.content]));
|
||||
return sanitize(html||'',{allowedTags:['p','br','div','span','b','strong','i','em','u','s','ul','ol','li','blockquote','pre','code','h1','h2','h3','h4','table','thead','tbody','tfoot','tr','th','td','hr','img'],allowedAttributes:{'*':['style'],td:['colspan','rowspan','style'],th:['colspan','rowspan','style'],img:['src','alt','width','height']},allowedStyles:{'*':{'color':[/^#[0-9a-f]{3,8}$/i,/^[a-z]+$/i],'background-color':[/^#[0-9a-f]{3,8}$/i,/^[a-z]+$/i],'text-align':[/^(left|right|center)$/],'font-weight':[/^(bold|normal|[1-9]00)$/],'font-size':[/^\d{1,2}(px|pt)$/],'border':[/^\dpx solid #[0-9a-f]{3,6}$/i],'padding':[/^\d{1,2}px$/]}},allowedSchemes:['data'],allowedSchemesByTag:{img:['data']},transformTags:{img:(tag,attrs)=>{const src=attrs.src?.startsWith('cid:')?(inline.get(attrs.src.slice(4))||''):attrs.src||'';expandedBytes+=src.length;if(expandedBytes>12*1024*1024)fail('内嵌图片展开超过 12 MB,请减少重复图片后重新发送。');return {tagName:'img',attribs:{...attrs,src}};}},exclusiveFilter:frame=>frame.tag==='img'&&!/^data:image\/(png|jpeg|gif|webp);base64,[A-Za-z0-9+/=]+$/.test(frame.attribs.src||'')});
|
||||
}
|
||||
async function parseTemplate(raw,channel){
|
||||
if(!Buffer.isBuffer(raw)||raw.length>MAX_MAIL)fail('邮件超过 10 MB 限制。');
|
||||
const mail=await simpleParser(raw,{skipImageLinks:true,skipTextToHtml:true,maxHtmlLengthToParse:1024*1024,maxInlinedImagesSize:MAX_MAIL});
|
||||
const sourceSubject=(mail.subject||'').trim();if(!sourceSubject.startsWith('[模板]'))return null;
|
||||
let title=sourceSubject.slice(4).trim(),scope='';
|
||||
if(title.startsWith('[')){const scoped=/^\[([^\[\]\r\n]{1,80})\]\s*(.+)$/u.exec(title);if(!scoped||!scoped[1].trim())fail('模板主题范围或标题不完整。');scope=scoped[1].trim();title=scoped[2].trim();}
|
||||
if(!title)fail('模板主题缺少发信标题。');
|
||||
if(mail.inReplyTo || mail.references?.length)fail('回复邮件不作为模板,请新建邮件发送。');
|
||||
const senders=mail.from?.value||[];const sender=senders[0]?.address?.toLowerCase();
|
||||
if(senders.length!==1||!(channel.senders||[]).map(x=>x.toLowerCase()).includes(sender))fail('模板发件人不在允许名单中。');
|
||||
const recipients=[...(mail.to?.value||[]),...(mail.cc?.value||[])].map(x=>x.address?.toLowerCase());if(!recipients.includes(channel.email.toLowerCase()))fail('模板邮件收件人不包含此托管邮箱。');
|
||||
const subject=title;if(subject.length>300||!subject)fail('发信标题应为 1–300 字。');
|
||||
if((mail.html||'').length>1024*1024||(mail.text||'').length>200000)fail('模板正文过大。');
|
||||
const attachments=mail.attachments.map(a=>({filename:(a.filename||'附件').replace(/[\\/\x00-\x1f]/g,'_').slice(0,150),contentType:a.contentType,content:a.content.toString('base64'),cid:a.contentId?.replace(/^<|>$/g,''),size:a.content.length,inline:a.contentDisposition==='inline'}));
|
||||
const text=mail.text||'',html=cleanHtml(mail.html||'',attachments);if(!text.trim()&&!html.trim())fail('模板正文为空。');validateVariables(subject,text,html);
|
||||
return {subject,scope,text,html,sender,sourceSubject:mail.subject,messageId:mail.messageId||'',date:mail.date?.toISOString()||'',attachments,notes:[...(html?'': ['纯文本邮件']),...(/(^|\n)\s*(On .+wrote:|发件人[::]|-----Original Message-----|在.+写道[::])/im.test(text)?['正文包含引用内容,请核对后确认。']:[])]};
|
||||
}
|
||||
function renderTemplate(template,values){
|
||||
validateVariables(template.subject,template.text,template.html);
|
||||
const replace=(input,html)=>String(input||'').replace(/{{\s*(产品线|订单号|日期|订单列表)\s*}}/g,(_,key)=>{if(values[key]===undefined)fail('缺少模板变量:'+key);return html?escape(values[key]).replace(/\r?\n/g,'<br>'):String(values[key]);});
|
||||
let html=template.html?replace(template.html,true):undefined;
|
||||
for(const a of template.attachments||[])if(html&&a.cid&&/^[A-Za-z0-9._@+-]{1,200}$/.test(a.cid))html=html.replaceAll('src="data:'+a.contentType+';base64,'+a.content+'"','src="cid:'+a.cid+'"');
|
||||
return {subject:replace(template.subject,false).replace(/[\r\n]/g,' '),text:replace(template.text,false),html};
|
||||
}
|
||||
module.exports={parseTemplate,renderTemplate,cleanHtml,validateVariables,escape,MAX_MAIL};
|
||||
Reference in new issue
Block a user