'use strict'; const {test}=require('node:test');const assert=require('node:assert/strict'); const {MailService}=require('../../src/modules/mail/service.cjs'); const fs=require('node:fs'),os=require('node:os'),path=require('node:path'); const {MailStore}=require('../../src/modules/mail/store.cjs'); const {readHistory}=require('../../src/modules/mail/history.cjs'); const raw=Buffer.from('From: sender@example.test\r\nTo: orders@example.test\r\nCc: factory@example.test\r\nSubject: Order notice\r\nDate: Sun, 18 Oct 2026 10:00:00 +0800\r\nMessage-ID: \r\nContent-Type: text/plain; charset=utf-8\r\n\r\nOrder body'); function fixture(){ const calls=[],store={channelSecret:()=>({version:1,imap:{}}),guard(){}}; const client={mailbox:{uidValidity:9n},on(){},async connect(){},async logout(){},close(){},async list(){return [{path:'Sent',specialUse:'\\Sent',flags:new Set()},{path:'INBOX',flags:new Set()}];},async getMailboxLock(folder,options){calls.push({folder,...options});return {release(){}};},async search(query,options){calls.push({query,...options});return [1,2,3];},async fetchOne(uid,query,options){calls.push({uid,query,...options});return query.source?{source:raw}:{uid,size:raw.length,envelope:{subject:'Order notice',date:new Date('2026-10-18T02:00:00Z'),to:[{address:'orders@example.test'}]}};}}; client.fetch=async function*(range,query,options){for(const uid of range.split(',').map(Number))yield await client.fetchOne(uid,query,options);}; const service=new MailService({store,imapFactory:()=>client,smtpFactory:()=>{throw Error('SMTP must not be used');}}); return {service,calls,client}; } test('history batches bounded UID envelopes, keeps descending order and releases its read lock',async()=>{ let locked=false,released=0,batches=0; const client={mailbox:{uidValidity:42n},list:async()=>[{path:'Sent',specialUse:'\\Sent'}], async getMailboxLock(folder,options){assert.equal(folder,'Sent');assert.equal(options.readOnly,true);locked=true;return {release(){locked=false;released++;}};}, async search(query,options){assert.equal(locked,true);assert.equal(options.uid,true);return [3,8,5,10,2];}, fetchOne(){assert.fail('search must not fetch each message separately');}, async *fetch(range,query,options){batches++;assert.equal(locked,true);assert.equal(range,'10,8,5');assert.deepEqual(query,{uid:true,envelope:true,size:true});assert.deepEqual(options,{uid:true}); // An expunged UID is absent; sequence order need not equal the requested order. yield {uid:5,size:100,envelope:{subject:'Five'}};yield {uid:10,envelope:{subject:'Ten'}}; yield {uid:10,size:200};yield {uid:99,size:1,envelope:{subject:'Unrequested'}};yield {seq:1,flags:new Set()}; } }; const result=await readHistory(client,{action:'search',folder:'Sent',since:'2026-10-01',before:'2026-10-02',limit:3}); assert.deepEqual(result.messages.map(item=>[item.uid,item.subject,item.size]),[[10,'Ten',200],[5,'Five',100]]);assert.equal(result.uidValidity,'42');assert.equal(result.truncated,true);assert.equal(batches,1);assert.equal(released,1);assert.equal(locked,false); }); test('empty history search never FETCHes and an interrupted batch always releases its lock',async()=>{ let released=0; const client={mailbox:{uidValidity:9n},list:async()=>[{path:'Sent',specialUse:'\\Sent'}],getMailboxLock:async()=>({release(){released++;}}),search:async()=>[], fetchOne:()=>assert.fail('no per-message fetch'),async *fetch(){assert.fail('empty results must not become a wildcard fetch');} }; const input={action:'search',folder:'Sent',since:'2026-10-01',before:'2026-10-02'}; assert.deepEqual((await readHistory(client,input)).messages,[]);assert.equal(released,1); client.search=async()=>[4];client.fetch=async function*(){throw Error('batch interrupted');}; await assert.rejects(readHistory(client,input),/batch interrupted/);assert.equal(released,2); }); test('an IMAP-only history account stores no SMTP credential and rejects all sending or template polling',async t=>{ const dir=fs.mkdtempSync(path.join(os.tmpdir(),'history-account-')),store=new MailStore(dir); const service=new MailService({store,smtpFactory:()=>{throw Error('SMTP should be unreachable');}}); t.after(async()=>{await service.stop();store.close();fs.rmSync(dir,{recursive:true,force:true});}); const account=store.saveChannel({readOnly:true,name:'历史格式核对',email:'orders@example.test',imap:{host:'imap.example.test',port:993,security:'tls',user:'orders@example.test',password:'History-only-123'}}); assert.equal(account.readOnly,true);assert.equal(account.enabled,false);assert.equal(account.smtp.hasPassword,false); assert.doesNotMatch(JSON.stringify(store.channels()),/History-only-123/); for(const work of [()=>service.verify(account.id),()=>service.poll(account.id),()=>service.sendTest(account.id,'any')])await assert.rejects(work(),e=>e.status===409&&e.message.includes('只读')); }); test('sent history is bounded, read-only, does not download bodies during search, and keeps mailbox cursor untouched',async()=>{ const {service,calls}=fixture(); const result=await service.history('channel',{action:'search',folder:'Sent',since:'2026-10-01',before:'2026-10-20',subject:'订单',limit:2}); assert.equal(result.messages.length,2);assert.equal(result.truncated,true);assert.deepEqual(result.messages.map(m=>m.uid),[3,2]); assert.ok(calls.some(c=>c.folder==='Sent'&&c.readOnly===true)); assert.ok(calls.some(c=>c.query?.sentSince instanceof Date&&c.query.subject==='订单')); assert.ok(!calls.some(c=>c.query?.source)); const detail=await service.history('channel',{action:'message',folder:'Sent',uid:3,uidValidity:result.uidValidity}); assert.equal(detail.text,'Order body');assert.equal(detail.to[0].address,'orders@example.test');assert.equal(detail.cc[0].address,'factory@example.test'); assert.deepEqual(detail.attachments,[]); }); test('history rejects wrong folder, stale UID epoch, oversized messages and unbounded dates without leaking provider errors',async()=>{ const {service,client}=fixture(); for(const input of [{action:'search',folder:'INBOX',since:'2026-10-01',before:'2026-10-20'},{action:'search',folder:'Sent',since:'2020-01-01',before:'2026-10-20'},{action:'search',folder:'Sent',since:'2026-02-31',before:'2026-03-05'}])await assert.rejects(service.history('c',input),e=>e.status===400); await assert.rejects(service.history('c',{action:'message',folder:'Sent',uid:3,uidValidity:'8'}),e=>e.status===409); client.fetchOne=async()=>({size:20*1024*1024}); await assert.rejects(service.history('c',{action:'message',folder:'Sent',uid:3,uidValidity:'9'}),e=>e.status===413); client.connect=async()=>{throw Error('secret password');}; await assert.rejects(service.history('c',{action:'folders'}),e=>!e.message.includes('secret password')); });