fix: close merge-review mail policy and repair validation gaps

This commit is contained in:
abaishu0730 committed 2026-10-27 14:38:36 +08:00
1 parent dcea4a063f
commit d744c36365
16 files changed
+168 -31

No files matched your search

+1
View File
@@ -43,3 +43,4 @@ test('dashboard asset initialization failure closes the already-created session
Module._resolveFilename=function(id,...rest){if(id==='@tabler/core/dist/css/tabler.min.css')throw new Error('fixture missing asset');return originalResolve.call(this,id,...rest);};SessionStore.prototype.close=function(){closed++;return originalClose.call(this);};
try{assert.throws(()=>createDashboard({store:new Store(path.join(dir,'dashboard')),outputDir:dir}),/fixture missing asset/);assert.equal(closed,1);}finally{Module._resolveFilename=originalResolve;SessionStore.prototype.close=originalClose;}
});
test('application wires test expiry to every manual mail submission path',async t=>{const options=await fixture(t),app=await main(options);t.after(async()=>{await app.stop();await fs.rm(options.stateDir,{recursive:true,force:true});});app.orderRules.put('stability-test',{id:'main',enabled:true,startedAt:'2026-01-01T00:00:00Z',endsAt:'2026-01-02T00:00:00Z'});assert.throws(()=>app.mail.beforeSend(),e=>e.code==='STABILITY_TEST_EXPIRED');});
+24
View File
@@ -0,0 +1,24 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path'),{execFileSync,spawnSync}=require('node:child_process');
test('host repair validator runs fixed and changed tests in a foreign-owned isolated checkout',t=>{
const base=fs.mkdtempSync(path.join(os.tmpdir(),'repair-validator-'));
t.after(()=>fs.rmSync(base,{recursive:true,force:true}));
const host=path.join(base,'host'),repo=path.join(base,'repo'),checkout=path.join(base,'checkout'),validator=path.join(host,'src','modules','assistant','repair-validator.cjs');
fs.mkdirSync(path.dirname(validator),{recursive:true});fs.mkdirSync(path.join(repo,'tests'),{recursive:true});
fs.copyFileSync(path.resolve(__dirname,'../../src/modules/assistant/repair-validator.cjs'),validator);
fs.writeFileSync(path.join(host,'package.json'),JSON.stringify({scripts:{'test:business':'node --test --test-concurrency=1 tests/fixed.test.cjs'}}));
const git=(cwd,...args)=>execFileSync('git',['-c','user.name=Test','-c','user.email=test@example.invalid',...args],{cwd,encoding:'utf8',stdio:['ignore','pipe','pipe']});
const receipt=path.join(base,'ran-tests.txt'),testSource=name=>"require('node:test')("+JSON.stringify(name)+",()=>require('node:fs').appendFileSync("+JSON.stringify(receipt)+","+JSON.stringify(name+'\n')+"));";
fs.writeFileSync(path.join(repo,'tests/fixed.test.cjs'),testSource('fixed manifest test'));
git(repo,'init');git(repo,'add','.');git(repo,'commit','-m','baseline');git(repo,'worktree','add','--detach',checkout);
fs.writeFileSync(path.join(checkout,'tests/changed.test.cjs'),testSource('changed repair test'));
git(checkout,'add','.');git(checkout,'commit','-m','proposal');
const env={...process.env,GIT_CONFIG_NOSYSTEM:'1',GIT_CONFIG_GLOBAL:process.platform==='win32'?'NUL':'/dev/null',GIT_TEST_ASSUME_DIFFERENT_OWNER:'1'};
delete env.NODE_TEST_CONTEXT; // Production runner also excludes test-runner internals.
const result=spawnSync(process.execPath,[validator],{cwd:checkout,env,encoding:'utf8',windowsHide:true});
assert.equal(result.status,0,result.stderr);assert.deepEqual(fs.readFileSync(receipt,'utf8').trim().split('\n').sort(),['changed repair test','fixed manifest test']);
// Trust applies to this one invocation; it must not persist globally or locally.
const untrusted=spawnSync('git',['rev-parse','HEAD'],{cwd:checkout,env,encoding:'utf8',windowsHide:true});
assert.notEqual(untrusted.status,0);assert.match(untrusted.stderr,/dubious ownership/);
});
+4 -4
View File
@@ -4,11 +4,11 @@ const config={name:'邮箱',email:'orders@company.test',smtp:{host:'smtp.company
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('self-test renders business template variables with synthetic data and the configured self recipient',async t=>{
let sent;const {store,service}=await fixture(t,{smtpFactory:()=>({verify:async()=>{},sendMail:async message=>{sent=message;return {accepted:[config.email]};},close(){}})});
test('self-test renders business template variables with synthetic data and the fixed isolated QQ recipient',async t=>{
let sent;const {store,service}=await fixture(t,{smtpFactory:()=>({verify:async()=>{},sendMail:async message=>{sent=message;return {accepted:['2639266652@qq.com']};},close(){}})});
const c=store.saveChannel({...config,signature:{enabled:true,format:'html',body:'<p>Best Regards! 隔离账户签名</p>'}}),p=require('../../src/modules/mail/parser.cjs'),body='{{类别名称}}\n{{订单明细}}\n存放地址:{{存放地址}}',mail=Buffer.from(raw.toString().replace('Hello {{订单号}}',body));
const draft=store.ingest(c.id,'1',1,await p.parseTemplate(mail,config),mail,c.version);store.confirm(draft.id,{version:1,subject:'测试摘要',scope:'',text:body,useText:true},'admin');
await service.sendTest(c.id,draft.id);assert.equal(sent.to.address,config.email);assert.match(sent.text,/订单号:TEST/);assert.match(sent.text,/示例归档目录/);assert.match(sent.text,/隔离账户签名/);assert.match(sent.html,/<p>Best Regards!/);assert.doesNotMatch(sent.text,/{{/);assert.equal(store.sends()[0].status,'sent');
await service.sendTest(c.id,draft.id);assert.deepEqual(sent.to,['2639266652@qq.com']);assert.deepEqual(sent.cc,[]);assert.deepEqual(sent.attachments,[]);assert.match(sent.text,/订单号:TEST/);assert.match(sent.text,/示例归档目录/);assert.match(sent.text,/隔离账户签名/);assert.match(sent.html,/<p>Best Regards!/);assert.doesNotMatch(sent.text,/{{/);assert.equal(store.sends()[0].status,'sent');
});
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(){}};
@@ -22,5 +22,5 @@ test('initial empty seven-day scan retains date boundary on future polls',async
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');
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,'2639266652@qq.com');assert.match(sent.text,/Hello TEST/);assert.equal(store.sends()[0].status,'sent');
});
+22
View File
@@ -0,0 +1,22 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict');
const {MailService}=require('../../src/modules/mail/service.cjs');
function fixture({verify=()=>{},beforeSend=()=>{},unknown=false}={}){
const rows=[],messages=[],template={id:'template',version:1,status:'active',channelId:'channel',subject:'Template',text:'Hello {{订单号}}',html:'',attachments:[{filename:'private.pdf',content:'cGRm',contentType:'application/pdf'}]};
const store={channelSecret:()=>({id:'channel',version:1,email:'sender@company.test',name:'Sender',smtp:{}}),guard(){},template:()=>({...template}),sends:()=>rows,findSampleSend:(id,key)=>rows.find(r=>r.channel_id===id&&r.template_id===key),beginSend:(id,key)=>{rows.push({id:'send-'+rows.length,channel_id:id,template_id:key,status:'sending'});return rows.at(-1).id;},finishSend:(id,status)=>{rows.find(r=>r.id===id).status=status;}};
const service=new MailService({store,beforeSend,smtpFactory:()=>({verify:async()=>verify(template),sendMail:async message=>{messages.push(message);if(unknown)throw Error('connection lost');return {accepted:['2639266652@qq.com'],rejected:[]};},close(){}})});
return {service,rows,messages,template};
}
test('legacy template test enforces fixed QQ envelope without source attachments',async()=>{
const f=fixture(),result=await f.service.sendTest('channel','template');assert.equal(result.to,'2639266652@qq.com');assert.deepEqual(f.messages[0].to,['2639266652@qq.com']);assert.deepEqual(f.messages[0].cc,[]);assert.deepEqual(f.messages[0].attachments,[]);
});
for(const action of ['sendTest','sendSample'])for(const phase of ['before','after'])test(action+' enforces active period '+phase+' SMTP verification',async()=>{
let verified=false;const f=fixture({verify:()=>{verified=true;},beforeSend:()=>{if(phase==='before'||verified)throw Object.assign(Error('expired'),{status:409});}});
await assert.rejects(()=>action==='sendTest'?f.service.sendTest('channel','template'):f.service.sendSample('channel',{idempotencyKey:'one',subject:'Sample',text:'Hello'}),e=>e.status===409);assert.equal(f.messages.length,0);assert.equal(f.rows.length,0);assert.equal(verified,phase==='after');
});
test('template changed during SMTP verification is not submitted',async()=>{
const f=fixture({verify:t=>{t.version++;}});await assert.rejects(()=>f.service.sendTest('channel','template'),e=>e.status===409);assert.equal(f.messages.length,0);
});
test('uncertain template test cannot be repeated',async()=>{
const f=fixture({unknown:true});await assert.rejects(()=>f.service.sendTest('channel','template'));assert.equal(f.rows[0].status,'unknown');await assert.rejects(()=>f.service.sendTest('channel','template'),e=>e.status===409);assert.equal(f.messages.length,1);
});
@@ -0,0 +1,14 @@
'use strict';
// Keep the real server entrypoint and OS lifecycle, replacing business startup
// so this crash test cannot access company systems or production state.
const fs=require('node:fs'),http=require('node:http'),path=require('node:path');
const {respondToPing}=require('../../../src/platform/service/ping.cjs');
const application=require.resolve('../../../src/app/application.cjs');
require.cache[application]={id:application,filename:application,loaded:true,exports:{async main(){
const dir=process.env.ORDER_CRASH_TEST_DIR,port=Number(process.env.ORDER_CRASH_TEST_PORT);let ticks=0;
const server=http.createServer((req,res)=>respondToPing(req,res,{token:process.env.ORDER_SUPERVISOR_TOKEN,instanceId:process.env.ORDER_SUPERVISOR_INSTANCE,startedAt:new Date().toISOString()}));
await new Promise(resolve=>server.listen(port,'127.0.0.1',resolve));
fs.writeFileSync(path.join(dir,'child.pid'),String(process.pid));
const timer=setInterval(()=>fs.writeFileSync(path.join(dir,'ticks'),String(++ticks)),40);
return {async stop(){clearInterval(timer);await new Promise(resolve=>server.close(resolve));}};
}}};
@@ -0,0 +1,4 @@
'use strict';
const path=require('node:path');
const {ServiceSupervisor}=require('../../../src/platform/service/supervisor.cjs');
new ServiceSupervisor({stateDir:process.env.ORDER_CRASH_TEST_DIR,ports:[Number(process.env.ORDER_CRASH_TEST_PORT)],env:{NODE_OPTIONS:'--require "'+path.join(__dirname,'crash-service-preload.cjs').replaceAll('\\','/')+'"'},timing:{intervalMs:50,pingTimeoutMs:100,startupGraceMs:3000}}).start().catch(error=>{console.error(error);process.exit(1);});
+20
View File
@@ -0,0 +1,20 @@
'use strict';
const {test}=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs/promises'),os=require('node:os'),path=require('node:path'),net=require('node:net'),{spawn}=require('node:child_process');
const pause=ms=>new Promise(resolve=>setTimeout(resolve,ms));
const crash=guard=>process.platform==='win32'?require('node:child_process').execFileSync('powershell.exe',['-NoProfile','-NonInteractive','-Command','Stop-Process -Id '+guard.pid+' -Force'],{windowsHide:true}):guard.kill('SIGKILL');
const alive=pid=>{try{process.kill(pid,0);return true;}catch{return false;}};
async function until(predicate,timeout=5000){const end=Date.now()+timeout;while(Date.now()<end){if(await predicate())return true;await pause(40);}return false;}
async function freePort(){const socket=net.createServer();await new Promise(resolve=>socket.listen(0,'127.0.0.1',resolve));const port=socket.address().port;await new Promise(resolve=>socket.close(resolve));return port;}
async function fixture(t){
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'order-guard-crash-')),port=await freePort();let childPid;
const guard=spawn(process.execPath,[path.resolve('tests/service/fixtures/crash-supervisor.cjs')],{cwd:process.cwd(),windowsHide:true,detached:true,stdio:'ignore',env:{...process.env,ORDER_CRASH_TEST_DIR:dir,ORDER_CRASH_TEST_PORT:String(port)}});
t.after(async()=>{if(alive(guard.pid))guard.kill('SIGKILL');if(childPid&&alive(childPid))process.kill(childPid,'SIGKILL');await until(()=>!alive(guard.pid)&&(!childPid||!alive(childPid)));await fs.rm(dir,{recursive:true,force:true});});
assert.equal(await until(async()=>{try{childPid=Number(await fs.readFile(path.join(dir,'child.pid'),'utf8'));return Number(await fs.readFile(path.join(dir,'ticks'),'utf8'))>1;}catch{return false;}}),true,'isolated child must start');
return {dir,port,guard,childPid};
}
test('Windows abrupt supervisor death stops its business child and releases its listening port',{timeout:15000,skip:process.platform!=='win32'},async t=>{
const {dir,port,guard,childPid}=await fixture(t);crash(guard);
assert.equal(await until(()=>!alive(childPid)),true,'orphan business child must exit after supervisor death');
const ticks=await fs.readFile(path.join(dir,'ticks'),'utf8');await pause(150);assert.equal(await fs.readFile(path.join(dir,'ticks'),'utf8'),ticks,'scheduled work must cease');
const socket=net.createServer();await new Promise((resolve,reject)=>{socket.once('error',reject);socket.listen(port,'127.0.0.1',resolve);});await new Promise(resolve=>socket.close(resolve));
});