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
@@ -0,0 +1,32 @@
|
||||
'use strict';
|
||||
const {secureBpmTransport}=require('../bpm/api.cjs');const {escape}=require('./parser.cjs');
|
||||
const fail=(message,status)=>{throw Object.assign(new Error(message),{status});};
|
||||
async function mailApi({mail,workspace,user,route,method,body,request,response,reply,trustedProxy}){
|
||||
if(!route.startsWith('/api/mail'))return false;if(!mail)fail('邮件服务暂不可用。',503);const store=mail.store;
|
||||
if(method==='POST'&&user.role!=='admin')fail('仅管理员可以维护邮箱和确认模板。',403);
|
||||
if(route==='/api/mail'&&method==='GET'){reply(200,{channels:store.channels(),templates:store.templates(),receipts:store.receipts(),sends:store.sends()});return true;}
|
||||
const audit=(action,detail)=>workspace?.record(user,action,detail);
|
||||
if(route==='/api/mail/channels'&&method==='POST'){
|
||||
if(!secureBpmTransport(request,trustedProxy))fail('请在部署机本地或 HTTPS 页面维护邮箱账号。',403);
|
||||
if(body?.id&&mail.busy(body.id))fail('此邮箱正在执行操作,请稍后保存。',409);const saved=store.saveChannel(body);audit('mail.channel.save',saved.name);reply(body.id?200:201,saved);return true;
|
||||
}
|
||||
let match=/^\/api\/mail\/channels\/([\w-]+)\/(verify|poll|test)$/.exec(route);
|
||||
if(match&&method==='POST'){const [,id,action]=match;let result;if(action==='test'){if(typeof body.templateId!=='string')fail('请选择已生效模板。',400);result=await mail.sendTest(id,body.templateId);}else result=await mail[action](id);audit('mail.'+action,store.publicChannel(id).name);reply(200,result);return true;}
|
||||
match=/^\/api\/mail\/templates\/([\w-]+)(?:\/(confirm|reject|preview|source|attachments\/([0-9]+)))?$/.exec(route);
|
||||
if(match){const [,id,action,index]=match;const template=store.template(id);
|
||||
if(method==='GET'&&!action){const {raw,attachments,...detail}=template;reply(200,{...detail,attachments:attachments.map(({content,...a})=>a)});return true;}
|
||||
if(method==='GET'&&action==='preview'){
|
||||
response.setHeader('Content-Security-Policy',"default-src 'none'; img-src data:; style-src 'unsafe-inline'; sandbox; base-uri 'none'; form-action 'none'");
|
||||
response.writeHead(200,{'Content-Type':'text/html; charset=utf-8'});response.end('<!doctype html><html lang="zh-CN"><meta charset="utf-8"><style>body{font:14px/1.7 system-ui,sans-serif;padding:16px;color:#182433;overflow-wrap:anywhere}img{max-width:100%;height:auto}table{border-collapse:collapse;max-width:100%}td,th{padding:6px;border:1px solid #ddd}pre{white-space:pre-wrap}</style><body>'+(template.html||'<pre>'+escape(template.text)+'</pre>')+'</body></html>');return true;
|
||||
}
|
||||
if(method==='GET'&&(action==='source'||action?.startsWith('attachments/'))){
|
||||
if(user.role!=='admin')fail('仅管理员可以下载原邮件和附件。',403);let bytes,name;
|
||||
if(action==='source'){bytes=store.source(id);name='template.eml';}else{const a=template.attachments[Number(index)];if(!a)fail('附件不存在。',404);bytes=Buffer.from(a.content,'base64');name=a.filename;}
|
||||
response.writeHead(200,{'Content-Type':'application/octet-stream','Content-Disposition':"attachment; filename*=UTF-8''"+encodeURIComponent(name)});response.end(bytes);return true;
|
||||
}
|
||||
if(method==='POST'&&action==='confirm'){const saved=store.confirm(id,body,user.username);audit('mail.template.confirm',saved.subject);reply(200,{id:saved.id,status:saved.status,version:saved.version});return true;}
|
||||
if(method==='POST'&&action==='reject'){store.reject(id,body.version);audit('mail.template.reject',template.subject);reply(200,{ok:true});return true;}
|
||||
}
|
||||
fail('没有找到此邮件操作。',404);
|
||||
}
|
||||
module.exports={mailApi};
|
||||
@@ -0,0 +1,37 @@
|
||||
'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};
|
||||
@@ -0,0 +1,29 @@
|
||||
'use strict';
|
||||
const {ImapFlow}=require('imapflow');const nodemailer=require('nodemailer');const {parseTemplate,renderTemplate,MAX_MAIL}=require('./parser.cjs');
|
||||
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;}
|
||||
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));}
|
||||
async withImap(config,work){const client=this.imapFactory(config);client.on?.('error',()=>{});this.clients.add(client);try{await client.connect();return await work(client);}finally{try{await client.logout();}catch{}client.close?.();this.clients.delete(client);}}
|
||||
verify(id){return this.exclusive(id,async()=>{const c=this.store.channelSecret(id);let smtp=false,imap=false,message='SMTP 与 IMAP 连接正常';const transport=this.smtpFactory(c.smtp);this.clients.add(transport);try{try{await transport.verify();smtp=true;}catch(e){message=safeError(e,'SMTP');}try{await this.withImap(c.imap,async client=>{const lock=await client.getMailboxLock('INBOX',{readOnly:true});lock.release();});imap=true;}catch(e){message+=(smtp?'':';')+(smtp?'': ' ');message=smtp?safeError(e,'IMAP'):message+safeError(e,'IMAP');}this.store.setState(id,c.version,{checkedAt:new Date().toISOString(),smtp,imap,message});return this.store.publicChannel(id);}finally{transport.close?.();this.clients.delete(transport);}});}
|
||||
poll(id){return this.exclusive(id,async()=>{const c=this.store.channelSecret(id);if(!c.enabled)fail('请先启用此邮箱的模板收信。',409);let imported=0,rejected=0;try{
|
||||
await this.withImap(c.imap,async client=>{const lock=await client.getMailboxLock('INBOX',{readOnly:true});try{const epoch=String(client.mailbox.uidValidity),cursor=this.store.cursor(id);const sameEpoch=cursor.epoch===epoch;const last=sameEpoch?(cursor.uid||0):0;const query={since:new Date(sameEpoch&&cursor.since?cursor.since:Date.now()-7*86400000),...(last?{uid:(last+1)+':*'}:{})};const found=await client.search(query,{uid:true});const uids=(found||[]).filter(uid=>uid>last).sort((a,b)=>a-b).slice(0,50);
|
||||
for(const uid of uids){if(this.stopped)break;this.store.guard(id,c.version);const info=await client.fetchOne(uid,{envelope:true,size:true},{uid:true});if(!info){this.store.skip(id,epoch,uid,'skipped','邮件已移除',c.version);continue;}
|
||||
if(!/^\[模板\]/.test((info.envelope?.subject||'').trim())){this.store.transaction(()=>{this.store.guard(id,c.version);this.store.advance(id,epoch,uid);});continue;}
|
||||
if(!Number.isFinite(info.size)||info.size>MAX_MAIL){this.store.skip(id,epoch,uid,'rejected','邮件超过 10 MB 限制',c.version);rejected++;continue;}
|
||||
const source=await client.fetchOne(uid,{source:true},{uid:true});if(!source){this.store.skip(id,epoch,uid,'skipped','邮件已移除',c.version);continue;}
|
||||
let parsed;try{parsed=await parseTemplate(source.source,c);}catch(e){this.store.skip(id,epoch,uid,'rejected',e.status===400?e.message:'邮件格式无法解析,请重新发送模板。',c.version);rejected++;continue;}
|
||||
if(parsed){const result=this.store.ingest(id,epoch,uid,parsed,source.source,c.version);if(result.created)imported++;}else this.store.skip(id,epoch,uid,'skipped','未包含模板指令',c.version);
|
||||
}
|
||||
// Persist an empty mailbox epoch too, without skipping future messages.
|
||||
if(!uids.length&&!sameEpoch)this.store.transaction(()=>{this.store.guard(id,c.version);this.store.advance(id,epoch,0);});
|
||||
}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),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'};const rendered=renderTemplate(t,values);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);}});}
|
||||
start(){this.stopped=false;const tick=()=>{for(const c of this.store.channels())if(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()]);}
|
||||
}
|
||||
module.exports={MailService};
|
||||
@@ -0,0 +1,66 @@
|
||||
'use strict';
|
||||
const path=require('node:path');const crypto=require('node:crypto');const {DatabaseSync}=require('node:sqlite');const {BpmVault}=require('../../platform/security/vault.cjs');const {validateVariables}=require('./parser.cjs');
|
||||
const fail=(message,status=400)=>{throw Object.assign(new Error(message),{status});};
|
||||
const email=value=>{if(typeof value!=='string'||value.length>254||!/^[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?\.[A-Za-z]{2,63}$/.test(value.trim()))fail('请输入有效的邮箱地址。');return value.trim().toLowerCase();};
|
||||
const text=(v,label,max=200)=>{if(typeof v!=='string'||!v.trim()||v.length>max||/[\x00-\x1f]/.test(v))fail(label+'格式不正确。');return v.trim();};
|
||||
const at=()=>new Date().toISOString();const hash=raw=>crypto.createHash('sha256').update(raw).digest('hex');
|
||||
class MailStore{
|
||||
constructor(dir){this.vault=new BpmVault({stateDir:path.join(dir,'secrets')});this.db=new DatabaseSync(path.join(dir,'mail.sqlite'));this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000; PRAGMA secure_delete=ON;
|
||||
CREATE TABLE IF NOT EXISTS channels(id TEXT PRIMARY KEY,email TEXT NOT NULL UNIQUE,version INTEGER NOT NULL,payload BLOB NOT NULL,state TEXT NOT NULL,cursor TEXT NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS templates(id TEXT PRIMARY KEY,channel_id TEXT NOT NULL,source_key TEXT NOT NULL,scope TEXT NOT NULL,status TEXT NOT NULL,version INTEGER NOT NULL,base_id TEXT,payload BLOB NOT NULL,created_at TEXT NOT NULL,UNIQUE(channel_id,source_key));
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS active_template ON templates(channel_id,scope) WHERE status='active';
|
||||
CREATE TABLE IF NOT EXISTS receipts(id INTEGER PRIMARY KEY,channel_id TEXT NOT NULL,epoch TEXT NOT NULL,uid INTEGER NOT NULL,status TEXT NOT NULL,detail TEXT NOT NULL,at TEXT NOT NULL,UNIQUE(channel_id,epoch,uid));
|
||||
CREATE TABLE IF NOT EXISTS sends(id TEXT PRIMARY KEY,channel_id TEXT NOT NULL,template_id TEXT NOT NULL,status TEXT NOT NULL,at TEXT NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS meta(key TEXT PRIMARY KEY,value TEXT NOT NULL);`);
|
||||
if(!this.db.prepare('PRAGMA table_info(templates)').all().some(c=>c.name==='summary'))this.db.exec("ALTER TABLE templates ADD COLUMN summary TEXT NOT NULL DEFAULT '{}'");
|
||||
for(const r of this.db.prepare("SELECT id,payload FROM templates WHERE summary='{}'").all()){const p=this.decode(r.id,r.payload);this.db.prepare('UPDATE templates SET summary=? WHERE id=?').run(this.summary(p),r.id);}
|
||||
}
|
||||
summary(p){return JSON.stringify({subject:p.subject,sender:p.sender,attachmentCount:p.attachments.length});}
|
||||
recoverSends(){this.db.prepare("UPDATE sends SET status='unknown' WHERE status='sending'").run();}
|
||||
transaction(work){this.db.exec('BEGIN IMMEDIATE');try{const result=work();this.db.exec('COMMIT');return result;}catch(e){this.db.exec('ROLLBACK');throw e;}}
|
||||
encode(id,value){try{return this.vault.encode(id,value);}catch{fail('邮件加密存储不可用,请联系管理员。',503);}}
|
||||
decode(id,value){try{return this.vault.decode(id,value);}catch{fail('邮件加密存储不可用,请联系管理员。',503);}}
|
||||
row(id){const row=this.db.prepare('SELECT * FROM channels WHERE id=?').get(id);if(!row)fail('邮箱不存在。',404);return row;}
|
||||
channelSecret(id){const row=this.row(id);return {...this.decode(id,row.payload),id,version:row.version};}
|
||||
publicChannel(id){const c=this.channelSecret(id),state=JSON.parse(this.row(id).state);return {...c,smtp:{...c.smtp,password:undefined,hasPassword:!!c.smtp.password},imap:{...c.imap,password:undefined,hasPassword:!!c.imap.password},state};}
|
||||
channels(){return this.db.prepare('SELECT id FROM channels ORDER BY rowid').all().map(r=>this.publicChannel(r.id));}
|
||||
saveChannel(input){return this.transaction(()=>{
|
||||
if(!input||typeof input!=='object')fail('邮箱配置无效。');const old=input.id?this.channelSecret(input.id):null;if(old&&old.version!==input.version)fail('邮箱已被修改,请刷新后重试。',409);
|
||||
const id=old?.id||crypto.randomUUID(),address=email(input.email);const existing=this.db.prepare('SELECT id FROM channels WHERE email=?').get(address);if(existing&&existing.id!==id)fail('此邮箱已托管,请使用已有邮箱。',409);
|
||||
if(typeof input.enabled!=='boolean'||!Array.isArray(input.senders)||!input.senders.length||input.senders.length>100)fail('请填写模板发件人名单,并选择是否启用收信。');
|
||||
const endpoint=kind=>{const v=input[kind];if(!v||!['tls','starttls'].includes(v.security)||!Number.isInteger(v.port)||v.port<1||v.port>65535)fail(kind.toUpperCase()+' 端口或加密方式无效。');const host=text(v.host,'服务器地址',253);if(!/^[a-zA-Z0-9.:-]+$/.test(host)||host.startsWith('-'))fail('服务器地址只填写主机名或 IP。');const password=v.password===''&&old?old[kind].password:v.password;if(typeof password!=='string'||!password||password.length>2048)fail('请输入 '+kind.toUpperCase()+' 密码或授权码。');const user=text(v.user,'登录账号',254);if(old&&v.password===''&&(old.email!==address||old[kind].user!==user||old[kind].host!==host))fail('更换邮箱、服务器或登录账号时,请重新填写密码。');return {host,port:v.port,security:v.security,user,password};};
|
||||
const saved={name:text(input.name,'邮箱名称',80),email:address,smtp:endpoint('smtp'),imap:endpoint('imap'),senders:[...new Set(input.senders.map(email))],enabled:input.enabled,createdAt:old?.createdAt||at(),updatedAt:at()};
|
||||
const reset=!old||old.email!==address||JSON.stringify(old.imap)!==JSON.stringify(saved.imap);const oldrow=old?this.row(id):null;
|
||||
const changed=reset||JSON.stringify(old?.smtp)!==JSON.stringify(saved.smtp);const state=changed?{checkedAt:null,smtp:false,imap:false,pollAt:null,message:'待检查连接'}:JSON.parse(oldrow.state);
|
||||
this.db.prepare('INSERT INTO channels VALUES(?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET email=excluded.email,version=excluded.version,payload=excluded.payload,state=excluded.state,cursor=excluded.cursor').run(id,address,(old?.version||0)+1,this.encode(id,saved),JSON.stringify(state),reset?'{}':oldrow.cursor);return this.publicChannel(id);
|
||||
});}
|
||||
guard(id,version){if(this.row(id).version!==version)fail('邮箱配置已变化,请重试。',409);}
|
||||
setState(id,version,patch){this.guard(id,version);this.db.prepare('UPDATE channels SET state=? WHERE id=?').run(JSON.stringify({...JSON.parse(this.row(id).state),...patch}),id);}
|
||||
cursor(id){return JSON.parse(this.row(id).cursor);}
|
||||
advance(id,epoch,uid){const prior=this.cursor(id);this.db.prepare('UPDATE channels SET cursor=? WHERE id=?').run(JSON.stringify({epoch:String(epoch),uid,since:prior.epoch===String(epoch)&&prior.since?prior.since:new Date(Date.now()-7*86400000).toISOString()}),id);}
|
||||
receipt(id,epoch,uid,status,detail){this.db.prepare('INSERT OR IGNORE INTO receipts(channel_id,epoch,uid,status,detail,at) VALUES(?,?,?,?,?,?)').run(id,String(epoch),uid,status,detail,at());this.db.prepare('DELETE FROM receipts WHERE channel_id=? AND id NOT IN (SELECT id FROM receipts WHERE channel_id=? ORDER BY id DESC LIMIT 500)').run(id,id);}
|
||||
skip(id,epoch,uid,status,detail,version){return this.transaction(()=>{this.guard(id,version);this.receipt(id,epoch,uid,status,detail);this.advance(id,epoch,uid);});}
|
||||
receipts(){return this.db.prepare('SELECT * FROM receipts ORDER BY id DESC LIMIT 100').all();}
|
||||
ingest(channelId,epoch,uid,parsed,raw,configVersion){return this.transaction(()=>{
|
||||
this.guard(channelId,configVersion);const key=parsed.messageId?hash(parsed.messageId+'\0'+hash(raw)):hash(raw);const old=this.db.prepare('SELECT id FROM templates WHERE channel_id=? AND source_key=?').get(channelId,key);
|
||||
let id=old?.id;if(!id){id=crypto.randomUUID();const payload={...parsed,raw:raw.toString('base64')};const base=this.activeId(channelId,parsed.scope);this.db.prepare('INSERT INTO templates VALUES(?,?,?,?,?,?,?,?,?,?)').run(id,channelId,key,parsed.scope,'pending',1,base,this.encode(id,payload),at(),this.summary(parsed));}
|
||||
this.receipt(channelId,epoch,uid,old?'duplicate':'pending',old?'已识别,未重复导入':'待确认模板');this.advance(channelId,epoch,uid);return {...this.template(id),created:!old};
|
||||
});}
|
||||
template(id){const r=this.db.prepare('SELECT * FROM templates WHERE id=?').get(id);if(!r)fail('模板不存在。',404);return {...this.decode(id,r.payload),id:r.id,channelId:r.channel_id,scope:r.scope,status:r.status,version:r.version,baseId:r.base_id,createdAt:r.created_at};}
|
||||
templates(){return ['pending','active','archived','rejected'].flatMap(status=>this.db.prepare('SELECT id,channel_id,scope,status,version,created_at,summary FROM templates WHERE status=? ORDER BY created_at DESC,rowid DESC LIMIT 200').all(status).map(r=>({...JSON.parse(r.summary),id:r.id,channelId:r.channel_id,scope:r.scope,status:r.status,version:r.version,createdAt:r.created_at})));}
|
||||
stats(){return Object.fromEntries(this.db.prepare('SELECT status,COUNT(*) AS count FROM templates GROUP BY status').all().map(r=>[r.status,r.count]));}
|
||||
activeId(channelId,scope){return this.db.prepare("SELECT id FROM templates WHERE channel_id=? AND scope=? AND status='active'").get(channelId,scope)?.id||null;}
|
||||
active(channelId,scope){const r=this.db.prepare("SELECT id FROM templates WHERE channel_id=? AND scope=? AND status='active'").get(channelId,scope);return r?this.template(r.id):null;}
|
||||
confirm(id,input,actor){return this.transaction(()=>{const t=this.template(id);if(t.status!=='pending'||input.version!==t.version)fail('模板状态已变化,请刷新。',409);if(t.channelId==='legacy'){this.row(input.channelId);t.channelId=input.channelId;}const subject=text(input.subject,'邮件标题',300);if(typeof input.scope!=='string'||input.scope.length>80||/[\[\]\x00-\x1f]/.test(input.scope))fail('产品线格式无效。');const scope=input.scope.trim(),current=this.activeId(t.channelId,scope);if(current!==(scope===t.scope?t.baseId:null))fail('该范围已有更新的模板,请重新导入后确认。',409);
|
||||
if(typeof input.useText!=='boolean')fail('正文模式无效。');if(input.useText){if(typeof input.text!=='string'||!input.text.trim()||input.text.length>200000)fail('正文应为 1–200000 字。');t.text=input.text;t.html='';}
|
||||
validateVariables(subject,t.text,t.html);const payload={...t,subject,scope,confirmedBy:actor,confirmedAt:at()};delete payload.id;this.db.prepare("UPDATE templates SET status='archived',version=version+1 WHERE channel_id=? AND scope=? AND status='active'").run(t.channelId,scope);this.db.prepare("UPDATE templates SET channel_id=?,scope=?,status='active',version=version+1,payload=?,summary=? WHERE id=?").run(t.channelId,scope,this.encode(id,payload),this.summary(payload),id);return this.template(id);
|
||||
});}
|
||||
reject(id,version){const t=this.template(id);if(t.status!=='pending'||t.version!==version)fail('模板状态已变化。',409);this.db.prepare("UPDATE templates SET status='rejected',version=version+1 WHERE id=?").run(id);}
|
||||
source(id){return Buffer.from(this.template(id).raw||'','base64');}
|
||||
migrateLegacy(legacy){if(this.db.prepare("SELECT 1 FROM meta WHERE key='legacy'").get())return;this.transaction(()=>{if(legacy?.subject?.trim()&&legacy?.body?.trim()){const id=crypto.randomUUID(),payload={subject:legacy.subject,text:legacy.body,html:'',sender:'工作台旧草稿',sourceSubject:legacy.subject,attachments:[],notes:['从原模板草稿迁入,请选择托管邮箱后确认。']};this.db.prepare('INSERT INTO templates VALUES(?,?,?,?,?,?,?,?,?,?)').run(id,'legacy','legacy','','pending',1,null,this.encode(id,payload),at(),this.summary(payload));}this.db.prepare("INSERT INTO meta VALUES('legacy','1')").run();});}
|
||||
beginSend(channelId,templateId){const id=crypto.randomUUID();this.db.prepare('INSERT INTO sends VALUES(?,?,?,?,?)').run(id,channelId,templateId,'sending',at());return id;}
|
||||
finishSend(id,status){this.db.prepare('UPDATE sends SET status=? WHERE id=?').run(status,id);}
|
||||
sends(){return this.db.prepare('SELECT * FROM sends ORDER BY at DESC LIMIT 50').all();}
|
||||
close(){if(this.db){this.db.close();this.db=null;}this.vault.destroy();}
|
||||
}
|
||||
module.exports={MailStore,email};
|
||||
Reference in new issue
Block a user