fix: close merge-review mail policy and repair validation gaps
This commit is contained in:
1 parent
dcea4a063f
commit
d744c36365
16 files changed
+168
-31
No files matched your search
@@ -4,5 +4,8 @@ const fs=require('node:fs'),path=require('node:path'),{spawnSync,execFileSync}=r
|
||||
const root=path.resolve(__dirname,'../../..'),script=JSON.parse(fs.readFileSync(path.join(root,'package.json'),'utf8')).scripts['test:business'];
|
||||
if(!script.startsWith('node --test --test-concurrency=1 '))throw Error('Unexpected fixed business validation command');
|
||||
const baseline=script.slice('node --test --test-concurrency=1 '.length).split(' ');if(baseline.some(f=>!/^tests\/[\w./-]+\.test\.cjs$/.test(f)))throw Error('Invalid fixed test manifest');
|
||||
const changed=execFileSync('git',['-c','core.fsmonitor=false','diff','--name-only','HEAD~1','HEAD'],{encoding:'utf8',windowsHide:true}).trim().split(/\r?\n/).filter(f=>/^tests\/[\w./-]+\.test\.cjs$/.test(f));
|
||||
const run=spawnSync(process.execPath,['--test','--test-concurrency=1',...new Set([...baseline,...changed])],{cwd:process.cwd(),env:process.env,windowsHide:true,stdio:'inherit'});process.exitCode=run.status===0?0:1;
|
||||
// The runner supplies this isolated checkout. Trust only its canonical path for
|
||||
// this command; linked worktrees may have Git metadata on a shared filesystem.
|
||||
const cwd=fs.realpathSync.native(process.cwd()),normalized=cwd.replaceAll('\\','/'),safeDirectory=normalized.startsWith('//')?'%(prefix)/'+normalized:normalized;
|
||||
const changed=execFileSync('git',['-c','safe.directory='+safeDirectory,'-c','core.hooksPath=/dev/null','-c','core.fsmonitor=false','diff','--no-ext-diff','--no-textconv','--name-only','HEAD~1','HEAD','--'],{cwd,encoding:'utf8',windowsHide:true}).trim().split(/\r?\n/).filter(f=>/^tests\/[\w./-]+\.test\.cjs$/.test(f));
|
||||
const run=spawnSync(process.execPath,['--test','--test-concurrency=1',...new Set([...baseline,...changed])],{cwd,env:process.env,windowsHide:true,stdio:'inherit'});process.exitCode=run.status===0?0:1;
|
||||
@@ -3,17 +3,17 @@ const {ImapFlow}=require('imapflow');const nodemailer=require('nodemailer');cons
|
||||
const fail=(message,status=502)=>{throw Object.assign(new Error(message),{status});};
|
||||
const safeError=(error,kind)=>error?.code==='EAUTH'||error?.authenticationFailed?`${kind} 登录失败,请检查账号和授权密码。`:/CERT|TLS|SSL|SELF_SIGNED/.test(error?.code||'')?`${kind} 加密连接失败,请检查服务器地址和证书。`:`${kind} 连接失败,请检查服务器、端口和网络后重试。`;
|
||||
class MailService{
|
||||
constructor({store,imapFactory,smtpFactory,interval=60000}){this.store=store;this.imapFactory=imapFactory||((c)=>new ImapFlow({host:c.host,port:c.port,secure:c.security==='tls',doSTARTTLS:c.security==='starttls',auth:{user:c.user,pass:c.password},logger:false,disableAutoIdle:true,connectionTimeout:15000,greetingTimeout:15000,socketTimeout:30000,maxLiteralSize:MAX_MAIL,tls:{rejectUnauthorized:true,minVersion:'TLSv1.2'}}));this.smtpFactory=smtpFactory||((c)=>nodemailer.createTransport({host:c.host,port:c.port,secure:c.security==='tls',requireTLS:c.security==='starttls',auth:{user:c.user,pass:c.password},logger:false,debug:false,connectionTimeout:15000,greetingTimeout:15000,socketTimeout:30000,disableFileAccess:true,disableUrlAccess:true,tls:{rejectUnauthorized:true,minVersion:'TLSv1.2'}}));this.interval=interval;this.running=new Map();this.clients=new Set();this.stopped=false;}
|
||||
constructor({store,imapFactory,smtpFactory,interval=60000,beforeSend=()=>{}}){this.store=store;this.beforeSend=beforeSend;this.imapFactory=imapFactory||((c)=>new ImapFlow({host:c.host,port:c.port,secure:c.security==='tls',doSTARTTLS:c.security==='starttls',auth:{user:c.user,pass:c.password},logger:false,disableAutoIdle:true,connectionTimeout:15000,greetingTimeout:15000,socketTimeout:30000,maxLiteralSize:MAX_MAIL,tls:{rejectUnauthorized:true,minVersion:'TLSv1.2'}}));this.smtpFactory=smtpFactory||((c)=>nodemailer.createTransport({host:c.host,port:c.port,secure:c.security==='tls',requireTLS:c.security==='starttls',auth:{user:c.user,pass:c.password},logger:false,debug:false,connectionTimeout:15000,greetingTimeout:15000,socketTimeout:30000,disableFileAccess:true,disableUrlAccess:true,tls:{rejectUnauthorized:true,minVersion:'TLSv1.2'}}));this.interval=interval;this.running=new Map();this.clients=new Set();this.stopped=false;}
|
||||
busy(id){return this.running.has(id);}
|
||||
async exclusive(id,work){if(this.stopped)fail('邮件服务正在停止。',503);if(this.busy(id))fail('此邮箱正在执行操作,请稍后重试。',409);const promise=Promise.resolve().then(work);this.running.set(id,promise);return promise.finally(()=>this.running.delete(id));}
|
||||
sendSample(id,input){return this.exclusive(id,async()=>{
|
||||
if(!input||Object.keys(input).some(k=>!['idempotencyKey','subject','text'].includes(k))||typeof input.idempotencyKey!=='string'||!/^[\w-]{1,80}$/.test(input.idempotencyKey)||typeof input.subject!=='string'||!input.subject.trim()||input.subject.length>250||/[\x00-\x1f]/.test(input.subject)||typeof input.text!=='string'||!input.text.trim()||input.text.length>20000||input.text.includes('\0'))fail('样例测试内容无效。',400);
|
||||
const marker='sample:'+require('node:crypto').createHash('sha256').update(id+'\0'+input.idempotencyKey).digest('hex'),previous=this.store.findSampleSend(id,marker);
|
||||
if(previous){if(previous.status==='sent')return {id:previous.id,status:'sent',to:'2639266652@qq.com',reused:true};fail('此样例发送已有结果待核实,不会自动重发。',409);}
|
||||
const c=this.store.channelSecret(id);if(c.readOnly)fail('只读邮箱不能发信。',409);
|
||||
this.beforeSend();const c=this.store.channelSecret(id);if(c.readOnly)fail('只读邮箱不能发信。',409);
|
||||
const text='本邮件仅用于样例测试,不表示BPM已处理或PDF已归档。\n\n'+input.text,transport=this.smtpFactory(c.smtp);this.clients.add(transport);let sendId;
|
||||
try{
|
||||
await transport.verify();this.store.guard(id,c.version);sendId=this.store.beginSend(id,marker);
|
||||
await transport.verify();this.beforeSend();this.store.guard(id,c.version);sendId=this.store.beginSend(id,marker);
|
||||
const result=await transport.sendMail({from:{address:c.email,name:c.name},to:['2639266652@qq.com'],cc:[],subject:'[样例测试] '+input.subject,text,html:'<div>'+escape(text).replace(/\r?\n/g,'<br>')+'</div>',attachments:[],messageId:`<${sendId}@${c.email.split('@')[1]}>`,disableFileAccess:true,disableUrlAccess:true});
|
||||
if(result?.rejected?.length||!result?.accepted?.some(a=>String(a.address||a).toLowerCase()==='2639266652@qq.com'))throw Error('Sample recipient not fully accepted');
|
||||
this.store.finishSend(sendId,'sent');return {id:sendId,status:'sent',to:'2639266652@qq.com',messageId:result.messageId};
|
||||
@@ -41,7 +41,25 @@ class MailService{
|
||||
}finally{lock.release();}});
|
||||
this.store.setState(id,c.version,{imap:true,pollAt:new Date().toISOString(),message:`收信完成:新增 ${imported} 个模板,${rejected} 封未导入`});return {imported,rejected};
|
||||
}catch(error){if(error.status===409)throw error;const message=safeError(error,'IMAP');try{this.store.setState(id,c.version,{imap:false,pollAt:new Date().toISOString(),message});}catch{}fail(message);}});}
|
||||
sendTest(id,templateId){return this.exclusive(id,async()=>{const c=this.store.channelSecret(id);if(c.readOnly)fail('只读邮箱不能发送邮件。',409);const t=this.store.template(templateId);if(t.channelId!==id||t.status!=='active')fail('请选择此邮箱已确认生效的模板。',409);const values={'产品线':t.scope||'默认','订单号':'TEST','日期':new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Shanghai'}).format(new Date()),'订单列表':'测试订单 TEST','类别名称':'测试通知','订单明细':'订单号:TEST 机芯号:CORE 产品型号:MODEL 客户简称:示例 出货方式:CBU 总数量:1','存放地址':'示例归档目录(测试数据)'};const rendered=require('./content.cjs').appendSignature(renderTemplate(t,values),{...c.signature,channelId:c.id,version:c.version});const transport=this.smtpFactory(c.smtp);this.clients.add(transport);let sendId;try{await transport.verify();this.store.guard(id,c.version);sendId=this.store.beginSend(id,t.id);const result=await transport.sendMail({from:{address:c.email,name:c.name},to:{address:c.email},subject:'[测试] '+rendered.subject,text:rendered.text,html:rendered.html,messageId:`<${sendId}@${c.email.split('@')[1]}>`,disableFileAccess:true,disableUrlAccess:true,attachments:t.attachments.map(a=>({filename:a.filename,content:Buffer.from(a.content,'base64'),contentType:a.contentType,...(a.cid?{cid:a.cid}:{}),contentDisposition:a.inline?'inline':'attachment'}))});if(!result.accepted?.length)throw new Error('Recipient rejected');this.store.finishSend(sendId,'sent');return {id:sendId,status:'sent',to:c.email};}catch(e){if(sendId)this.store.finishSend(sendId,'unknown');if(e.status===409)throw e;fail(sendId?'发信结果待核对,请检查本邮箱后再决定是否重试。':safeError(e,'SMTP'));}finally{transport.close?.();this.clients.delete(transport);}});}
|
||||
sendTest(id,templateId){return this.exclusive(id,async()=>{
|
||||
this.beforeSend();
|
||||
const previous=this.store.findSampleSend(id,templateId);
|
||||
if(previous&&['sending','unknown'].includes(previous.status))fail('此模板测试发送结果待核实,禁止重复发送。',409);
|
||||
const c=this.store.channelSecret(id);if(c.readOnly)fail('只读邮箱不能发送邮件。',409);
|
||||
const t=this.store.template(templateId);if(t.channelId!==id||t.status!=='active')fail('请选择此邮箱已确认生效的模板。',409);
|
||||
const values={'产品线':t.scope||'默认','订单号':'TEST','日期':new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Shanghai'}).format(new Date()),'订单列表':'测试订单 TEST','类别名称':'测试通知','订单明细':'订单号:TEST 机芯号:CORE 产品型号:MODEL 客户简称:示例 出货方式:CBU 总数量:1','存放地址':'示例归档目录(测试数据)'};
|
||||
const rendered=require('./content.cjs').appendSignature(renderTemplate(t,values),{...c.signature,channelId:c.id,version:c.version});
|
||||
const transport=this.smtpFactory(c.smtp);this.clients.add(transport);let sendId;
|
||||
try{
|
||||
await transport.verify();this.beforeSend();this.store.guard(id,c.version);
|
||||
const current=this.store.template(templateId);if(current.version!==t.version||current.status!=='active'||current.channelId!==id)fail('模板已变化,请刷新后重试。',409);
|
||||
sendId=this.store.beginSend(id,t.id);
|
||||
const result=await transport.sendMail({from:{address:c.email,name:c.name},to:['2639266652@qq.com'],cc:[],subject:'[测试] '+rendered.subject,text:rendered.text,html:rendered.html,messageId:`<${sendId}@${c.email.split('@')[1]}>`,disableFileAccess:true,disableUrlAccess:true,attachments:[]});
|
||||
if(result?.rejected?.length||!result?.accepted?.some(a=>String(a.address||a).toLowerCase()==='2639266652@qq.com'))throw new Error('Test recipient not fully accepted');
|
||||
this.store.finishSend(sendId,'sent');return {id:sendId,status:'sent',to:'2639266652@qq.com'};
|
||||
}catch(e){if(sendId)this.store.finishSend(sendId,'unknown');if(e.status===409)throw e;fail(sendId?'发信结果待核实,请核对固定QQ收件箱,禁止重复发送。':safeError(e,'SMTP'));}
|
||||
finally{transport.close?.();this.clients.delete(transport);}
|
||||
});}
|
||||
start(){this.stopped=false;const tick=()=>{for(const c of this.store.channels())if(c.receiveEnabled!==false&&c.enabled&&!this.busy(c.id))this.poll(c.id).catch(()=>{});};this.timer=setInterval(tick,this.interval);this.timer.unref?.();this.startTimer=setTimeout(tick,2000);this.startTimer.unref?.();}
|
||||
async stop(){this.stopped=true;clearInterval(this.timer);clearTimeout(this.startTimer);for(const client of this.clients)try{client.close?.();}catch{}await Promise.allSettled([...this.running.values()]);}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user