feat: add category order rules and read-only sent mail history

This commit is contained in:
abaishu0730 committed 2026-10-19 10:36:32 +08:00
1 parent 388805a8a6
commit efa982a8a1
41 files changed
+1828 -28

No files matched your search

+8 -2
View File
@@ -4,13 +4,19 @@ 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;}
if(route==='/api/mail'&&method==='GET'){reply(200,{historyOnly:mail.historyOnly===true,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(mail.historyOnly&&body?.readOnly!==true)fail('此空间只允许配置只读 IMAP 邮箱。',409);
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);
let match=/^\/api\/mail\/channels\/([\w-]+)\/history$/.exec(route);
if(match&&method==='POST'){
const result=await mail.history(match[1],body);audit('mail.history.read',store.publicChannel(match[1]).name+' · '+String(body.action));reply(200,result);return true;
}
if(mail.historyOnly&&method==='POST')fail('此空间仅允许查询历史邮件,不能发信或收取模板。',409);
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);
+46
View File
@@ -0,0 +1,46 @@
'use strict';
const {simpleParser}=require('mailparser');
const {MAX_MAIL}=require('./parser.cjs');
const fail=(message,status=400)=>{throw Object.assign(new Error(message),{status});};
const sent=folder=>folder.specialUse==='\\Sent'||/^(?:sent|sent items|sent messages|已发送|已发送邮件)$/iu.test(folder.name||folder.path.split(folder.delimiter||'/').at(-1));
const addresses=values=>(values||[]).slice(0,100).map(({name,address})=>({name:name||'',address:address||''}));
function date(value){
if(typeof value!=='string'||!/^\d{4}-\d{2}-\d{2}$/.test(value))fail('请选择有效的查询日期。');
const result=new Date(value+'T00:00:00Z');if(!Number.isFinite(+result)||result.toISOString().slice(0,10)!==value)fail('查询日期无效。');return result;
}
async function readHistory(client,input={}){
if(!['folders','search','message'].includes(input.action))fail('请选择只读邮件查询操作。');
let query,limit;
if(input.action==='search'){
const since=date(input.since),before=date(input.before),span=before-since;
if(span<=0||span>31*86400000)fail('每次查询最多31天,结束日期不包含当天。');
limit=input.limit??20;if(!Number.isInteger(limit)||limit<1||limit>50)fail('每次最多显示50封邮件。');
if(input.subject!==undefined&&(typeof input.subject!=='string'||input.subject.length>100||/[\x00-\x1f]/.test(input.subject)))fail('主题关键词无效。');
query={sentSince:since,sentBefore:before,...(input.subject?.trim()?{subject:input.subject.trim()}: {})};
}
const folders=(await client.list()).filter(f=>sent(f)&&!f.flags?.has('\\Noselect')).map(f=>({path:f.path,name:f.name||f.path}));
if(input.action==='folders')return {folders};
if(!folders.some(f=>f.path===input.folder))fail('请选择服务器上的已发送文件夹。');
const lock=await client.getMailboxLock(input.folder,{readOnly:true});
try{
const uidValidity=String(client.mailbox.uidValidity);
if(input.action==='search'){
const found=await client.search(query,{uid:true}),uids=(found||[]).filter(Number.isSafeInteger).sort((a,b)=>b-a),messages=[];
for(const uid of uids.slice(0,limit)){
const info=await client.fetchOne(uid,{envelope:true,size:true},{uid:true});if(!info)continue;
messages.push({uid,subject:info.envelope?.subject||'',date:info.envelope?.date?.toISOString()||null,to:addresses(info.envelope?.to),cc:addresses(info.envelope?.cc),size:info.size});
}
return {folder:input.folder,uidValidity,messages,truncated:uids.length>limit};
}
if(!Number.isSafeInteger(input.uid)||input.uid<=0)fail('邮件标识无效。');
if(input.uidValidity!==uidValidity)fail('邮件文件夹已变化,请重新查询后打开。',409);
const info=await client.fetchOne(input.uid,{size:true},{uid:true});if(!info)fail('邮件已移除。',404);
if(!Number.isSafeInteger(info.size)||info.size>MAX_MAIL)fail('邮件超过10MB,仅可查看查询列表。',413);
const source=await client.fetchOne(input.uid,{source:true},{uid:true});if(!source?.source)fail('邮件已移除。',404);
if(source.source.length>MAX_MAIL)fail('邮件超过10MB,仅可查看查询列表。',413);
const parsed=await simpleParser(source.source,{skipHtmlToText:false,skipTextToHtml:true,skipImageLinks:true});
const text=parsed.text||'';
return {folder:input.folder,uid:input.uid,uidValidity,messageId:parsed.messageId||'',subject:parsed.subject||'',date:parsed.date?.toISOString()||null,from:addresses(parsed.from?.value),to:addresses(parsed.to?.value),cc:addresses(parsed.cc?.value),text:text.slice(0,100000),truncated:text.length>100000,attachments:parsed.attachments.map(a=>({filename:a.filename||'',size:a.size,contentType:a.contentType}))};
}finally{lock.release();}
}
module.exports={readHistory};
+8 -3
View File
@@ -7,8 +7,13 @@ class MailService{
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{
history(id,input){return this.exclusive(id,async()=>{
const config=this.store.channelSecret(id);
try{const result=await this.withImap(config.imap,client=>require('./history.cjs').readHistory(client,input));this.store.guard(id,config.version);return result;}
catch(error){if([400,404,409,413].includes(error.status))throw error;fail(safeError(error,'IMAP'));}
});}
verify(id){return this.exclusive(id,async()=>{const c=this.store.channelSecret(id);if(c.readOnly)fail('只读邮箱仅支持查询已发送邮件。',409);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.readOnly)fail('只读邮箱不能收取模板。',409);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;}
@@ -22,7 +27,7 @@ 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),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);}});}
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'};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()]);}
}
+5 -4
View File
@@ -29,14 +29,15 @@ class MailStore{
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};}
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 readOnly=input.readOnly===true;
if(!readOnly&&(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,readOnly,smtp:readOnly?{}:endpoint('smtp'),imap:endpoint('imap'),senders:readOnly?[]:[...new Set(input.senders.map(email))],enabled:readOnly?false: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);