fix: retain safe business access links in mail templates
This commit is contained in:
1 parent
d669a7b28e
commit
2fe5a3fe5d
2 files changed
+34
-1
No files matched your search
@@ -5,10 +5,18 @@ 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 safeLink(value){
|
||||
if(typeof value!=='string'||!/^https?:\/\/[^/?#]/i.test(value)||/[\s\p{Cc}\p{Cf}\\]/u.test(value))return false;
|
||||
try{
|
||||
if(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}\\]/u.test(decodeURIComponent(value)))return false;
|
||||
const url=new URL(value),authority=value.slice(value.indexOf('://')+3).split(/[/?#]/,1)[0];
|
||||
return ['http:','https:'].includes(url.protocol)&&!!url.hostname&&!url.username&&!url.password&&!authority.includes('@');
|
||||
}catch{return false;}
|
||||
}
|
||||
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||'')});
|
||||
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','a'],allowedAttributes:{'*':['style'],td:['colspan','rowspan','style'],th:['colspan','rowspan','style'],img:['src','alt','width','height'],a:['href','title']},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'],a:['http','https']},allowProtocolRelative:false,transformTags:{a:(tag,attrs)=>{if(safeLink(attrs.href))return {tagName:'a',attribs:attrs};const {href,...rest}=attrs;return {tagName:'span',attribs:rest};},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 限制。');
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
'use strict';
|
||||
const test=require('node:test'),assert=require('node:assert/strict');
|
||||
const {parseTemplate,cleanHtml}=require('../../src/modules/mail/parser.cjs');
|
||||
const {extractTitle}=require('../../src/modules/order-rules/title.cjs');
|
||||
const {ordersForMode}=require('../../src/modules/order-rules/huizhou.cjs');
|
||||
const {buildBatch}=require('../../src/modules/order-rules/batch.cjs');
|
||||
const {applyBodyTemplate}=require('../../src/modules/order-rules/template.cjs');
|
||||
const channel={email:'orders@example.test',senders:['author@example.test']};
|
||||
const raw=html=>Buffer.from('From: author@example.test\r\nTo: orders@example.test\r\nSubject: [模板]惠州 {{订单号}}\r\nMIME-Version: 1.0\r\nContent-Type: text/html; charset=utf-8\r\n\r\n'+html);
|
||||
test('imported business anchor survives real parsing and Hui rendering as a usable HTTPS link',async()=>{
|
||||
const parsed=await parseTemplate(raw('<p><a href="https://example.test/business">业务访问入口</a></p><p>{{订单明细}}</p><img src="https://tracker.example.test/pixel">'),channel);
|
||||
const rule={id:'notice',version:1,categoryId:'notice',name:'通知',to:['recipient@example.test'],cc:[],attachPdf:false,huizhouEnabled:true,huizhouTemplateId:'hui-link'};
|
||||
const title=extractTitle('订单号:O-100客户简称:普通客户业务模式:惠州数字毛利:绿标订单号:H-200客户简称:终端客户');
|
||||
const order={id:'event',status:'pending',ruleSnapshot:rule,event:{orderNo:'O-100',receivedAt:'2026-10-19T01:00:00Z',brief:title.brief,titleOrders:title.orders},archive:{archivedAt:'2026-10-19T02:00:00Z',files:[{name:'event.pdf',path:'C:\\archive\\event.pdf',kind:'pdf',size:100,sha256:'a'.repeat(64)}]}};
|
||||
const selected=ordersForMode([order],'huizhou'),snapshot=buildBatch(rule,selected,'2026-10-19T03:00:00Z',{notificationMode:'huizhou'});
|
||||
const mail=applyBodyTemplate(snapshot,{...parsed,id:'hui-link',version:1,status:'active',notificationMode:'huizhou'},selected,20971520);
|
||||
assert.match(mail.html,/<a href="https:\/\/example\.test\/business">业务访问入口<\/a>/);assert.match(mail.text,/https:\/\/example\.test\/business/);assert.match(mail.html,/H-200/);assert.doesNotMatch(mail.html,/O-100|tracker|<img/i);
|
||||
});
|
||||
test('sanitizer preserves absolute HTTP and HTTPS links but removes navigation side effects',()=>{
|
||||
const html=cleanHtml('<a href="http://example.test/business" onclick="attack()" ping="https://tracker.test/ping" target="_blank" download>HTTP</a><a href="https://example.test/business?q=one&mode=hui" onmouseover="attack()">HTTPS</a>');
|
||||
assert.match(html,/href="http:\/\/example\.test\/business"/);assert.match(html,/href="https:\/\/example\.test\/business\?q=one&mode=hui"/);assert.doesNotMatch(html,/onclick|onmouseover|ping=|target=|download|tracker|attack/i);
|
||||
});
|
||||
for(const href of ['javascript:alert(1)','javascript:alert(1)','data:text/html,hello','file:///C:/private','mailto:user@example.test','//example.test/business','/business','https://user:secret@example.test/business','https://user@example.test/business','https://@example.test/business','https://example.test/\nredirect',' https://example.test/business','https://example.test/%0aheader','https://example.test/%00','https:\\\\example.test\\business','https:///example.test/business'])test('sanitizer strips unsafe link target '+JSON.stringify(href),async()=>{
|
||||
const parsed=await parseTemplate(raw('<a href="'+href+'" onfocus="attack()">业务访问入口</a>'),channel);assert.match(parsed.html,/业务访问入口/);assert.doesNotMatch(parsed.html,/href=|onfocus|attack/i);
|
||||
});
|
||||
Reference in new issue
Block a user