refactor: organize source web and tests by business module

This commit is contained in:
abaishu0730 committed 2026-10-19 08:45:51 +08:00
1 parent 9854d2d5c2
commit 2aed328774
113 files changed
+189 -183

No files matched your search

+15
View File
@@ -0,0 +1,15 @@
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs');const os=require('node:os');const path=require('node:path');
const {Store}=require('../../src/modules/dashboard/store.cjs');const {createDashboard}=require('../../src/app/dashboard.cjs');const {MailStore}=require('../../src/modules/mail/store.cjs');const {MailService}=require('../../src/modules/mail/service.cjs');const {parseTemplate}=require('../../src/modules/mail/parser.cjs');
const config={name:'邮箱',email:'orders@company.test',smtp:{host:'smtp.company.test',port:465,security:'tls',user:'orders',password:'Secret-mail-123'},imap:{host:'imap.company.test',port:993,security:'tls',user:'orders',password:'Secret-mail-123'},senders:['author@company.test'],enabled:true};
async function setup(t){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'mail-http-'));const store=new Store(path.join(dir,'users'));store.bootstrap('admin','Test-password-123');store.addUser({username:'reader',password:'Test-password-123',role:'viewer'},'admin');const mailStore=new MailStore(path.join(dir,'mail'));const mail=new MailService({store:mailStore});const server=createDashboard({store,mail,outputDir:dir});await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(async()=>{await mail.stop();await new Promise(r=>server.close(r));mailStore.close();fs.rmSync(dir,{recursive:true,force:true});});const base='http://127.0.0.1:'+server.address().port;const call=(route,body,cookie,origin=base)=>fetch(base+route,{method:body===undefined?'GET':'POST',headers:{...(body===undefined?{}:{'Content-Type':'application/json',Origin:origin}),...(cookie?{Cookie:cookie}:{})},body:body===undefined?undefined:JSON.stringify(body)});const login=async username=>(await call('/api/login',{username,password:'Test-password-123'})).headers.get('set-cookie').split(';')[0];return {mail,mailStore,call,login};}
test('mail API uses authentication, roles, same origin, redacted config and actual overview status',async t=>{
const {mailStore,call,login}=await setup(t);assert.equal((await call('/api/mail')).status,401);const admin=await login('admin'),reader=await login('reader');assert.equal((await call('/api/mail/channels',config,reader)).status,403);assert.equal((await call('/api/mail/channels',config,admin,'https://evil.test')).status,403);
const save=await call('/api/mail/channels',config,admin);assert.equal(save.status,201);const c=await save.json();assert.equal(c.smtp.password,undefined);assert.equal(c.smtp.hasPassword,true);const snapshot=await (await call('/api/mail',undefined,reader)).json();assert.equal(snapshot.channels.length,1);assert.doesNotMatch(JSON.stringify(snapshot),/Secret-mail/);assert.equal((await call('/api/mail/channels',config,admin)).status,409);
mailStore.setState(c.id,1,{smtp:true,imap:true});const overview=await (await call('/api/overview',undefined,admin)).json();assert.equal(overview.connections.find(x=>x.name==='邮件渠道').ready,true);
});
test('template preview is isolated, source attachments downloadable and confirmation requires admin',async t=>{
const {mailStore,call,login}=await setup(t);const c=mailStore.saveChannel(config);const raw=Buffer.from('From: author@company.test\r\nTo: orders@company.test\r\nSubject: [模板]Notice\r\nMIME-Version: 1.0\r\nContent-Type: text/html\r\n\r\n<table><tr><td>Hello</td></tr></table>');const d=mailStore.ingest(c.id,'1',1,await parseTemplate(raw,config),raw,1);const admin=await login('admin'),reader=await login('reader');
const view=await call('/api/mail/templates/'+d.id+'/preview',undefined,reader);assert.equal(view.status,200);assert.match(view.headers.get('content-security-policy'),/sandbox/);assert.match(await view.text(),/<table>/);const detail=await (await call('/api/mail/templates/'+d.id,undefined,admin)).json();assert.equal(detail.raw,undefined);
assert.equal((await call('/api/mail/templates/'+d.id+'/confirm',{version:1,subject:d.subject,scope:'',useText:false},reader)).status,403);assert.equal((await call('/api/mail/templates/'+d.id+'/confirm',{version:1,subject:d.subject,scope:'',useText:false},admin)).status,200);assert.equal(mailStore.active(c.id,'').id,d.id);
assert.equal((await call('/api/mail/templates/'+d.id+'/source',undefined,reader)).status,403);const source=await call('/api/mail/templates/'+d.id+'/source',undefined,admin);assert.equal(await source.text(),raw.toString());
});
+19
View File
@@ -0,0 +1,19 @@
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs');const path=require('node:path');const os=require('node:os');const {SMTPServer}=require('smtp-server');const {simpleParser}=require('mailparser');
const {MailStore}=require('../../src/modules/mail/store.cjs');const {MailService}=require('../../src/modules/mail/service.cjs');
const config={name:'邮箱',email:'orders@company.test',smtp:{host:'smtp.company.test',port:465,security:'tls',user:'orders',password:'Secret-mail-123'},imap:{host:'imap.company.test',port:993,security:'tls',user:'orders',password:'Secret-mail-123'},senders:['author@company.test'],enabled:true};
const raw=Buffer.from('From: author@company.test\r\nTo: orders@company.test\r\nSubject: [模板]Notice\r\nMessage-ID: <a@company.test>\r\n\r\nHello {{订单号}}');
async function fixture(t,options={}){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'mail-service-'));const store=new MailStore(dir);const service=new MailService({store,...options});t.after(async()=>{await service.stop();store.close();fs.rmSync(dir,{recursive:true,force:true});});return {store,service};}
test('read-only poll uses UID epoch, ignores ordinary messages, does not double ingest, and records source denials',async t=>{
let downloads=0,locks=0;const client={mailbox:{uidValidity:10n},on(){},async connect(){},async getMailboxLock(box,options){assert.equal(box,'INBOX');assert.equal(options.readOnly,true);locks++;return {release(){locks--;}};},async search(query,options){assert.equal(options.uid,true);return [1,2,3];},async fetchOne(uid,query,options){assert.equal(options.uid,true);if(query.source){downloads++;return {source:uid===3?Buffer.from(raw.toString().replace('author@','unknown@')):raw};}return {size:raw.length,envelope:{subject:uid===1?'Ordinary':'[模板]Notice'}};},async logout(){},close(){}};
const {store,service}=await fixture(t,{imapFactory:()=>client});const c=store.saveChannel(config);await service.poll(c.id);await service.poll(c.id);assert.equal(downloads,2);assert.equal(locks,0);assert.equal(store.templates().length,1);assert.equal(store.cursor(c.id).uid,3);assert.equal(store.receipts()[0].status,'rejected');
});
test('failed download does not advance cursor and overlapping polls are blocked; provider error never exposes secret',async t=>{
let release;const wait=new Promise(r=>release=r);const client={mailbox:{uidValidity:1n},on(){},async connect(){await wait;},async getMailboxLock(){return {release(){}};},async search(){return [9];},async fetchOne(uid,q){if(q.source)throw new Error(config.imap.password);return {size:100,envelope:{subject:'[模板]Notice'}};},async logout(){},close(){}};
const {store,service}=await fixture(t,{imapFactory:()=>client});const c=store.saveChannel(config);const first=service.poll(c.id);await assert.rejects(service.poll(c.id),e=>e.status===409);release();await assert.rejects(first,e=>!e.message.includes(config.imap.password));assert.deepEqual(store.cursor(c.id),{});assert.doesNotMatch(JSON.stringify(store.channels()),/Secret-mail/);
});
test('initial empty seven-day scan retains date boundary on future polls',async t=>{const queries=[];const client={mailbox:{uidValidity:1n},on(){},async connect(){},async getMailboxLock(){return {release(){}};},async search(q){queries.push(q);return [];},async logout(){},close(){}};const {store,service}=await fixture(t,{imapFactory:()=>client});const c=store.saveChannel(config);await service.poll(c.id);await service.poll(c.id);assert.ok(queries[0].since instanceof Date);assert.ok(queries[1].since instanceof Date);assert.ok(Math.abs(queries[0].since-queries[1].since)<5000);});
test('SMTP verification never sends; explicit self-test uses confirmed template and durable send record',async t=>{
let messages=[];const smtp=new SMTPServer({secure:false,hideSTARTTLS:true,authOptional:true,disabledCommands:['AUTH'],onData(stream,session,cb){const chunks=[];stream.on('data',c=>chunks.push(c));stream.on('end',()=>{messages.push(Buffer.concat(chunks));cb();});}});await new Promise(r=>smtp.listen(0,'127.0.0.1',r));t.after(()=>new Promise(r=>smtp.close(r)));
const nodemailer=require('nodemailer');const {store,service}=await fixture(t,{smtpFactory:()=>nodemailer.createTransport({host:'127.0.0.1',port:smtp.server.address().port,secure:false,ignoreTLS:true}),imapFactory:()=>({on(){},async connect(){},async getMailboxLock(){return {release(){}};},async logout(){},close(){}})});
const c=store.saveChannel(config);await service.verify(c.id);assert.equal(messages.length,0);const p=require('../../src/modules/mail/parser.cjs');const draft=store.ingest(c.id,'1',1,await p.parseTemplate(raw,config),raw,c.version);assert.equal(store.active(c.id,''),null);await assert.rejects(service.sendTest(c.id,draft.id),e=>e.status===409);store.confirm(draft.id,{version:1,subject:'Notice {{订单号}}',scope:'',text:'Hello {{订单号}}',useText:false},'admin');await service.sendTest(c.id,draft.id);assert.equal(messages.length,1);const sent=await simpleParser(messages[0]);assert.equal(sent.to.value[0].address,config.email);assert.match(sent.text,/Hello TEST/);assert.equal(store.sends()[0].status,'sent');
});
+8
View File
@@ -0,0 +1,8 @@
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs');const os=require('node:os');const path=require('node:path');const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');const {Store}=require('../../src/modules/dashboard/store.cjs');const {createDashboard}=require('../../src/app/dashboard.cjs');const {MailStore}=require('../../src/modules/mail/store.cjs');const {MailService}=require('../../src/modules/mail/service.cjs');const {parseTemplate}=require('../../src/modules/mail/parser.cjs');
test('mail management saves a real config, previews template under CSP and confirms after review; narrow layout stays inside viewport',async t=>{
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'mail-ui-')),store=new Store(path.join(dir,'users'));store.bootstrap('admin','Test-password-123');const mailStore=new MailStore(path.join(dir,'mail')),mail=new MailService({store:mailStore});const server=createDashboard({store,mail,outputDir:dir});let browser;
t.after(async()=>{await browser?.close();await mail.stop();await new Promise(r=>server.close(r));mailStore.close();fs.rmSync(dir,{recursive:true,force:true});});await new Promise(r=>server.listen(0,'127.0.0.1',r));const base='http://127.0.0.1:'+server.address().port;browser=await loadPlaywright().chromium.launch(browserOptions());const page=await browser.newPage({viewport:{width:1360,height:950}});const errors=[];page.on('pageerror',e=>errors.push(e.message));await page.goto(base+'/#mail');await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();await page.getByRole('button',{name:'添加邮箱',exact:true}).click({timeout:5000});
await page.getByLabel('邮箱名称',{exact:true}).fill('通知邮箱');await page.getByLabel('邮箱地址',{exact:true}).fill('orders@company.test');for(const type of ['SMTP','IMAP']){await page.getByLabel(type+' 服务器',{exact:true}).fill(type.toLowerCase()+'.company.test');await page.getByLabel(type+' 登录账号',{exact:true}).fill('orders');await page.getByLabel(type+' 密码 / 授权码',{exact:true}).fill('Secret-mail-123');}await page.getByLabel('允许提交模板的发件人',{exact:true}).fill('author@company.test');await page.getByRole('button',{name:'保存邮箱',exact:true}).click();await page.getByText('通知邮箱',{exact:true}).waitFor();assert.equal(mailStore.channels().length,1);
const c=mailStore.channels()[0],raw=Buffer.from('From: author@company.test\r\nTo: orders@company.test\r\nSubject: [模板]Notice\r\nMIME-Version: 1.0\r\nContent-Type: text/html\r\n\r\n<table><tr><td>Template body</td></tr></table><img src="https://tracker.test/1">');const draft=mailStore.ingest(c.id,'1',1,await parseTemplate(raw,c),raw,1);await page.getByRole('link',{name:'模板与收件群组',exact:true}).click();await page.getByRole('button',{name:'预览并确认',exact:true}).click();await page.frameLocator('iframe[title="邮件正文预览"]').getByText('Template body',{exact:true}).waitFor();assert.equal(mailStore.template(draft.id).status,'pending');await page.getByLabel('发信标题',{exact:true}).fill('Confirmed notice');await page.getByRole('button',{name:'确认生效',exact:true}).click();await page.getByText('模板已确认生效。',{exact:true}).waitFor();assert.equal(mailStore.template(draft.id).status,'active');
await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);assert.deepEqual(errors,[]);
});
+46
View File
@@ -0,0 +1,46 @@
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs');const os=require('node:os');const path=require('node:path');
const {parseTemplate,renderTemplate}=require('../../src/modules/mail/parser.cjs');
const {MailStore}=require('../../src/modules/mail/store.cjs');
const config={name:'通知邮箱',email:'Orders@company.test',smtp:{host:'smtp.company.test',port:465,security:'tls',user:'orders',password:'Secret-mail-123'},imap:{host:'imap.company.test',port:993,security:'tls',user:'orders',password:'Secret-mail-123'},senders:['author@company.test'],enabled:true};
const eml=(subject='[模板][海外运营]订单 {{订单号}}',body='你好,{{产品线}}\r\n{{订单列表}}',from='author@company.test')=>Buffer.from(`From: ${from}\r\nTo: orders@company.test\r\nSubject: =?UTF-8?B?${Buffer.from(subject).toString('base64')}?=\r\nMessage-ID: <test1@company.test>\r\nMIME-Version: 1.0\r\nContent-Type: text/plain; charset=utf-8\r\n\r\n${body}`);
async function fixture(t){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'mail-'));const store=new MailStore(dir);t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});});return {dir,store};}
test('template MIME decoding and subject scope use explicit command, not replies',async()=>{
const p=await parseTemplate(eml(),config);assert.equal(p.scope,'海外运营');assert.equal(p.subject,'订单 {{订单号}}');assert.match(p.text,/你好/);assert.equal(p.sender,'author@company.test');
assert.equal(await parseTemplate(eml('Re: [模板]订单'),config),null);assert.equal(await parseTemplate(eml('普通订单'),config),null);
await assert.rejects(parseTemplate(eml('[模板]订单','正文','stranger@company.test'),config),/发件人/);
await assert.rejects(parseTemplate(eml('[模板]订单','正文','author@company.test, stranger@company.test'),config),/发件人/);
await assert.rejects(parseTemplate(eml('[模板]订单 {{unknown}}'),config),/变量/);
for(const subject of ['[模板][]Notice','[模板][海外运营]','[模板][海外运营','[模板][ ]Notice'])await assert.rejects(parseTemplate(eml(subject),config),/主题|范围/);
await assert.rejects(parseTemplate(Buffer.alloc(10*1024*1024+1),config),/10 MB/);
});
test('HTML tables and inline images survive while scripts and remote tracking are removed; attachments retain bytes',async()=>{
const raw=Buffer.from('From: author@company.test\r\nTo: orders@company.test\r\nSubject: [模板]HTML\r\nMIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=x\r\n\r\n--x\r\nContent-Type: text/html; charset=utf-8\r\n\r\n<table><tr><td>{{产品线}}</td></tr></table><script>alert(1)</script><img src="https://tracker.test/x"><img src="cid:logo"><a href="javascript:alert(1)">bad</a>\r\n--x\r\nContent-Type: image/png\r\nContent-ID: <logo>\r\nContent-Disposition: inline; filename="logo.png"\r\nContent-Transfer-Encoding: base64\r\n\r\naGVsbG8=\r\n--x\r\nContent-Type: application/pdf\r\nContent-Disposition: attachment; filename="notice.pdf"\r\nContent-Transfer-Encoding: base64\r\n\r\ncGRm\r\n--x--');
const p=await parseTemplate(raw,config);assert.match(p.html,/<table>/);assert.match(p.html,/data:image\/png;base64,aGVsbG8=/);assert.doesNotMatch(p.html,/tracker|script|javascript/i);assert.equal(p.attachments.length,2);assert.equal(p.attachments[1].content,'cGRm');
const r=renderTemplate(p,{'产品线':'<海外>','订单号':'1','日期':'2026-10-16','订单列表':'A\nB'});assert.match(r.html,/&lt;海外&gt;/);
});
test('mailbox secrets encrypted, identity unique, versions checked, blank secrets preserve existing value',async t=>{
const {dir,store}=await fixture(t);const c=store.saveChannel(config);assert.equal(c.email,'orders@company.test');assert.equal(c.smtp.hasPassword,true);assert.equal(c.smtp.password,undefined);
assert.throws(()=>store.saveChannel({...config,email:' ORDERS@company.test '}),e=>e.status===409);
const updated=store.saveChannel({...config,id:c.id,version:c.version,smtp:{...config.smtp,password:''},imap:{...config.imap,password:''}});assert.equal(store.channelSecret(c.id).smtp.password,config.smtp.password);
assert.throws(()=>store.saveChannel({...config,id:c.id,version:1}),e=>e.status===409);
for(const file of fs.readdirSync(dir).filter(f=>f.startsWith('mail.sqlite')))assert.equal(fs.readFileSync(path.join(dir,file)).includes(Buffer.from(config.smtp.password)),false);
assert.equal(updated.version,2);
store.setState(c.id,2,{smtp:true,imap:true});const toggled=store.saveChannel({...config,id:c.id,version:2,enabled:false});assert.equal(toggled.state.smtp,true);assert.equal(toggled.state.imap,true);
});
test('ingestion deduplicates restart and confirmation preserves active/history with stale-draft conflict',async t=>{
const {dir,store}=await fixture(t);const c=store.saveChannel(config);const p=await parseTemplate(eml(),config);
const d=store.ingest(c.id,'1',4,p,eml(),c.version);assert.equal(store.ingest(c.id,'1',4,p,eml(),c.version).id,d.id);assert.equal(store.cursor(c.id).uid,4);assert.equal(store.active(c.id,'海外运营'),null);
const active=store.confirm(d.id,{version:1,subject:p.subject,scope:p.scope,text:p.text,useText:false},'admin');assert.equal(active.status,'active');
const p2=await parseTemplate(eml('[模板][海外运营]新标题'),config);p2.messageId='<two@test>';
const d2=store.ingest(c.id,'1',5,p2,eml(),c.version);p2.messageId='<three@test>';const d3=store.ingest(c.id,'1',6,p2,eml(),c.version);
store.confirm(d2.id,{version:1,subject:p2.subject,scope:p2.scope,text:p2.text,useText:false},'admin');assert.throws(()=>store.confirm(d3.id,{version:1,subject:p2.subject,scope:p2.scope,text:p2.text,useText:false},'admin'),e=>e.status===409);
assert.equal(store.template(d.id).status,'archived');store.close();const reopened=new MailStore(dir);try{assert.equal(reopened.cursor(c.id).uid,6);assert.equal(reopened.templates().length,3);assert.equal(reopened.channelSecret(c.id).smtp.password,config.smtp.password);}finally{reopened.close();}
});
test('source message duplicates under new UID and epoch never generate new version; changed config rejects old poll commits',async t=>{
const {store}=await fixture(t);const c=store.saveChannel(config),p=await parseTemplate(eml(),config);const first=store.ingest(c.id,'1',3,p,eml(),1);assert.equal(store.ingest(c.id,'2',99,p,eml(),1).id,first.id);assert.equal(store.templates().length,1);
store.saveChannel({...config,id:c.id,version:1,enabled:false});assert.throws(()=>store.ingest(c.id,'2',100,p,eml(),1),e=>e.status===409);assert.equal(store.cursor(c.id).uid,99);
});
module.exports={config,eml};
test('repeated CID references are rejected before expanding to unbounded HTML',()=>{const {cleanHtml}=require('../../src/modules/mail/parser.cjs');assert.throws(()=>cleanHtml('<img src="cid:logo">'.repeat(200),[{cid:'logo',contentType:'image/png',content:Buffer.alloc(100000).toString('base64')}]),e=>e.status===400&&/内嵌图片/.test(e.message));});
test('outgoing embedded images use MIME content IDs and template lists never decode raw messages',async t=>{const {store}=await fixture(t);const c=store.saveChannel(config);const parsed={subject:'Notice',scope:'',text:'Image',html:'<img src="data:image/png;base64,aGVsbG8=">',sender:'author@company.test',attachments:[{filename:'a.png',cid:'logo',contentType:'image/png',content:'aGVsbG8=',inline:true,size:5}]};const d=store.ingest(c.id,'1',1,parsed,Buffer.from('raw'),1);assert.match(renderTemplate(parsed,{}).html,/src="cid:logo"/);const decode=store.decode;store.decode=()=>{throw new Error('must not decode payload');};try{assert.equal(store.templates()[0].id,d.id);}finally{store.decode=decode;}});
test('legacy draft can be assigned once to a real mailbox without losing body',async t=>{const {store}=await fixture(t);const c=store.saveChannel(config);store.migrateLegacy({subject:'旧草稿',body:'保留正文'});const d=store.templates()[0];const saved=store.confirm(d.id,{version:1,channelId:c.id,subject:'正式标题',scope:'',useText:false},'admin');assert.equal(saved.channelId,c.id);assert.equal(saved.text,'保留正文');assert.equal(store.active(c.id,'').id,d.id);store.migrateLegacy({subject:'旧草稿',body:'保留正文'});assert.equal(store.templates().length,1);});