'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){ try { 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 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 '{}'"); this.transaction(()=>{ if(!this.db.prepare('PRAGMA table_info(templates)').all().some(c=>c.name==='notification_mode'))this.db.exec("ALTER TABLE templates ADD COLUMN notification_mode TEXT NOT NULL DEFAULT 'normal' CHECK(notification_mode IN ('normal','huizhou'))"); const columns=this.db.prepare('PRAGMA index_info(active_template)').all().map(c=>c.name).join(','); if(columns!=='channel_id,scope,notification_mode')this.db.exec("DROP INDEX IF EXISTS active_template; CREATE UNIQUE INDEX active_template ON templates(channel_id,scope,notification_mode) WHERE status='active'"); }); 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);} } catch(error) { try { this.db?.close(); } catch {} try { this.vault?.destroy(); } catch {} throw error; } } 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){const depth=this.transactionDepth||0,savepoint='mail_nested_'+depth;this.db.exec(depth?'SAVEPOINT '+savepoint:'BEGIN IMMEDIATE');this.transactionDepth=depth+1;try{const result=work();this.db.exec(depth?'RELEASE SAVEPOINT '+savepoint:'COMMIT');return result;}catch(error){if(depth){this.db.exec('ROLLBACK TO SAVEPOINT '+savepoint);this.db.exec('RELEASE SAVEPOINT '+savepoint);}else this.db.exec('ROLLBACK');throw error;}finally{this.transactionDepth=depth;}} 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 {receiveEnabled:true,...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(input.enabled!==undefined&&typeof input.enabled!=='boolean')fail('模板收信开关必须是布尔值。'); const readOnly=input.readOnly===true; const receiveEnabled=input.receiveEnabled===undefined?(old?.receiveEnabled??true):input.receiveEnabled;if(typeof receiveEnabled!=='boolean')fail('请选择是否启用 IMAP 收信。'); input=require('./account-config.cjs').expandAccount(input,old,address); const enabled=!readOnly&&receiveEnabled&&input.enabled===true; if(!readOnly&&(!Array.isArray(input.senders)||input.senders.length>100||(enabled&&!input.senders.length)))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,receiveEnabled,smtp:readOnly?{}:endpoint('smtp'),imap:receiveEnabled?endpoint('imap'):(old?.imap||{}),senders:readOnly?[]:[...new Set(input.senders.map(email))],enabled,createdAt:old?.createdAt||at(),updatedAt:at()}; if(input.signature!==undefined)saved.signature=require('./content.cjs').normalizeSignature(input.signature);else if(old?.signature)saved.signature=old.signature; const reset=!old||old.email!==address||JSON.stringify(old.imap)!==JSON.stringify(saved.imap);const oldrow=old?this.row(id):null; const changed=reset||old?.receiveEnabled!==receiveEnabled||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'),notificationBaseIds:{normal:this.activeId(channelId,parsed.scope),huizhou:this.activeId(channelId,parsed.scope,'huizhou')}};const base=payload.notificationBaseIds.normal;this.db.prepare('INSERT INTO templates(id,channel_id,source_key,scope,status,version,base_id,payload,created_at,summary,notification_mode) VALUES(?,?,?,?,?,?,?,?,?,?,?)').run(id,channelId,key,parsed.scope,'pending',1,base,this.encode(id,payload),at(),this.summary(parsed),'normal');} 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,notificationMode:r.notification_mode,status:r.status,version:r.version,baseId:r.base_id,createdAt:r.created_at};} signature(id){const c=this.channelSecret(id);return {channelId:c.id,version:c.version,...(c.signature||{enabled:false,format:'text',body:'',text:'',html:''})};} saveTemplate(id,input,actor){return this.transaction(()=>{ if(!input||typeof input!=='object'||Array.isArray(input)||Object.keys(input).some(k=>!['version','channelId','subject','scope','notificationMode','format','body'].includes(k)))fail('模板编辑参数无效。'); const previous=id?this.template(id):null;if(previous&&(!['pending','active'].includes(previous.status)||input.version!==previous.version))fail('模板版本已变化或属于历史版本,请刷新或复制后编辑。',409); const channelId=previous?.channelId==='legacy'?input.channelId:previous?.channelId||input.channelId; if(previous&&previous.channelId!=='legacy'&&input.channelId!==undefined&&input.channelId!==channelId)fail('现有模板不能更换邮箱,请复制后编辑。',409); if(this.channelSecret(channelId).readOnly)fail('只读邮箱不能维护发信模板。',409); const subject=text(input.subject,'邮件标题',300),scope=typeof input.scope==='string'?input.scope.trim():null,mode=input.notificationMode; if(scope===null||scope.length>80||/[\[\]\x00-\x1f]/.test(scope)||!['normal','huizhou'].includes(mode))fail('产品线或通知模式无效。'); if(previous?.status==='active'&&previous.notificationMode!==mode)fail('已生效模板不能改变通知模式,请复制为新模板。',409); const content=require('./content.cjs').normalizeBody(input,previous?.attachments||[]);validateVariables(subject,content.text,content.html); const current=this.activeId(channelId,scope,mode);if(previous?.status==='active'&¤t&¤t!==id)fail('该范围已有其他生效模板,请更换范围。',409); const payload={...(previous||{}),...content,bodyFormat:content.format,subject,scope,notificationMode:mode,attachments:previous?.attachments||[],sender:previous?.sender||actor+'(页面编辑)',sourceSubject:previous?.sourceSubject||subject,editedBy:actor,editedAt:at()};delete payload.id; if(previous?.status==='pending'||!previous)payload.notificationBaseIds={normal:this.activeId(channelId,scope),huizhou:this.activeId(channelId,scope,'huizhou')}; if(!previous){id=crypto.randomUUID();this.db.prepare('INSERT INTO templates(id,channel_id,source_key,scope,status,version,base_id,payload,created_at,summary,notification_mode) VALUES(?,?,?,?,?,?,?,?,?,?,?)').run(id,channelId,'manual:'+id,scope,'pending',1,payload.notificationBaseIds[mode],this.encode(id,payload),at(),this.summary(payload),mode);} else{ if(previous.status==='active'){const historyId=crypto.randomUUID();this.db.prepare('INSERT INTO templates(id,channel_id,source_key,scope,status,version,base_id,payload,created_at,summary,notification_mode) VALUES(?,?,?,?,?,?,?,?,?,?,?)').run(historyId,previous.channelId,'revision:'+id+':'+previous.version,previous.scope,'archived',previous.version,id,this.encode(historyId,previous),at(),this.summary(previous),previous.notificationMode);} this.db.prepare('UPDATE templates SET channel_id=?,scope=?,notification_mode=?,version=version+1,payload=?,summary=? WHERE id=?').run(channelId,scope,mode,this.encode(id,payload),this.summary(payload),id); } return this.template(id); });} templates(){return ['pending','active','archived','rejected'].flatMap(status=>this.db.prepare('SELECT id,channel_id,scope,notification_mode,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,notificationMode:r.notification_mode,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]));} categoryBindings(){return JSON.parse(this.db.prepare("SELECT value FROM meta WHERE key='categoryBindings'").get()?.value||'[]');} bindCategory(input){return this.transaction(()=>{ const categories=require('../order-rules/catalog.cjs').seedRules(); if(!input||Object.keys(input).some(k=>!['categoryId','templateId','version'].includes(k))||!categories.some(c=>c.id===input.categoryId)||typeof input.templateId!=='string')fail('请选择有效的 Excel 类别和模板。'); const bindings=this.categoryBindings(),old=bindings.find(b=>b.categoryId===input.categoryId); if(input.version!==(old?.version||0))fail('类别模板关联已变化,请刷新后重试。',409); if(input.templateId){const t=this.template(input.templateId);if(t.status!=='active'||t.notificationMode!=='normal')fail('只能关联普通通知已确认生效的模板。',409);} const saved={categoryId:input.categoryId,templateId:input.templateId,version:(old?.version||0)+1}; this.db.prepare("INSERT INTO meta VALUES('categoryBindings',?) ON CONFLICT(key) DO UPDATE SET value=excluded.value").run(JSON.stringify([...bindings.filter(b=>b.categoryId!==input.categoryId),saved]));return saved; });} categoryTemplate(categoryId){const binding=this.categoryBindings().find(b=>b.categoryId===categoryId);if(!binding?.templateId)return null;const template=this.template(binding.templateId);if(template.status!=='active')fail('类别关联的模板已变为历史版本,请重新确认关联。',409);return {...template,bindingVersion:binding.version};} activeId(channelId,scope,mode='normal'){return this.db.prepare("SELECT id FROM templates WHERE channel_id=? AND scope=? AND notification_mode=? AND status='active'").get(channelId,scope,mode)?.id||null;} active(channelId,scope,mode='normal'){const id=this.activeId(channelId,scope,mode);return id?this.template(id):null;} confirm(id,input,actor){return this.transaction(()=>{const t=this.template(id);if(t.status!=='pending'||input.version!==t.version)fail('模板状态已变化,请刷新。',409);const notificationMode=input.notificationMode===undefined?'normal':input.notificationMode;if(!['normal','huizhou'].includes(notificationMode))fail('通知模式无效。');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,notificationMode),base=t.notificationBaseIds?.[notificationMode]??(notificationMode==='normal'?t.baseId:null);if(current!==(scope===t.scope?base: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='';t.bodyFormat='text';t.body=t.text;} validateVariables(subject,t.text,t.html);const payload={...t,subject,scope,notificationMode,confirmedBy:actor,confirmedAt:at()};delete payload.id;this.db.prepare("UPDATE templates SET status='archived',version=version+1 WHERE channel_id=? AND scope=? AND notification_mode=? AND status='active'").run(t.channelId,scope,notificationMode);this.db.prepare("UPDATE templates SET channel_id=?,scope=?,notification_mode=?,status='active',version=version+1,payload=?,summary=? WHERE id=?").run(t.channelId,scope,notificationMode,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(id,channel_id,source_key,scope,status,version,base_id,payload,created_at,summary,notification_mode) VALUES(?,?,?,?,?,?,?,?,?,?,?)').run(id,'legacy','legacy','','pending',1,null,this.encode(id,payload),at(),this.summary(payload),'normal');}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;} findSampleSend(channelId,key){return this.db.prepare('SELECT id,status FROM sends WHERE channel_id=? AND template_id=? ORDER BY at DESC LIMIT 1').get(channelId,key);} 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};