import test from 'node:test';import assert from 'node:assert/strict'; import fs from 'node:fs/promises';import path from 'node:path';import os from 'node:os';import http from 'node:http';import net from 'node:net';import {spawn} from 'node:child_process';import {once} from 'node:events'; import {parseAttachments,b2Body} from './attachments.mjs'; const listen=server=>new Promise(resolve=>server.listen(0,'127.0.0.1',resolve)); test('Winlink API uploads to native WebMail, verifies storage, lists and downloads received attachments',async()=>{ const dir=await fs.mkdtemp(path.join(os.tmpdir(),'bpq-upload-')),root=path.join(dir,'station');let child,stored=null,nativePosts=0,nextId=0,killed=false,adminSaves=0; const mail=path.join(root,'BPQMailChat','Mail');await fs.mkdir(mail,{recursive:true}); const server=http.createServer(async(req,res)=>{try{ if(req.url==='/Webmail'){res.end('Mail');return;} if(req.url.startsWith('/WebMail/NewMsg')){res.end('Compose');return;} if(req.url.startsWith('/WebMail/EMSave')){ nativePosts++;const chunks=[];for await(const chunk of req)chunks.push(chunk); const form=await new Request('http://localhost/',{method:'POST',headers:{'Content-Type':req.headers['content-type']},body:Buffer.concat(chunks)}).formData(); assert.equal(form.get('To'),'RMS/ALICE@EXAMPLE.TEST');const files=await Promise.all(form.getAll('myFile[]').map(async f=>({name:f.name,data:Buffer.from(await f.arrayBuffer())})));assert.equal(files.length,2); const body=Buffer.from(form.get('Msg'));stored=Buffer.concat([Buffer.from('MID: local-fixture\r\nBody: '+body.length+'\r\n'+files.map(f=>'File: '+f.data.length+' '+f.name+'\r\n').join('')+'\r\n'),body,Buffer.from('\r\n'),...files.flatMap(f=>[f.data,Buffer.from('\r\n')])]); nextId=1;await fs.writeFile(path.join(mail,'m_000001.mes'),stored);res.end('Message Saved');return; } if(req.url.startsWith('/WebMail/WMDel/')){res.end('Not your message');return;} if(req.url.startsWith('/Mail/MsgSave')){let payload='';for await(const chunk of req)payload+=chunk;assert.equal(payload,'N0TEST|RMS|BID-fixture||ALICE@EXAMPLE.TEST|Attachment fixture|P|K|');killed=true;adminSaves++;res.end('Saved');return;} if(req.url.startsWith('/WebMail/WMALL')){res.end('Message List\r\n'+(nextId?' 1 17-Oct P'+(killed?'K':'N')+' 100 '+['RMS','','N0TEST'].map(s=>s.padEnd(7)).join(' ')+' Attachment fixture\r\n':''));return;} if(req.url==='/Mail/Status'){res.end('Messages');return;} if(req.url.startsWith('/Mail/MsgDetails')){res.end('

Message 1

'+Object.entries({BID:'BID-fixture',EFROM:'',From:'N0TEST',To:'RMS',Title:'Attachment fixture',VIA:'ALICE@EXAMPLE.TEST',Sent:'17-Oct 12:00Z',RX:'17-Oct 12:00Z'}).map(([k,v])=>'').join(''));return;} if(req.url.startsWith('/WebMail/WM?')){res.end('');return;} res.end('BPQ Ports'); }catch(e){res.statusCode=500;res.end(e.message);}}); try{ await listen(server);const probe=net.createServer();await listen(probe);const port=probe.address().port;await new Promise(resolve=>probe.close(resolve)); await fs.writeFile(path.join(root,'BPQ32.cfg'),'NODECALL=N0TEST-7\nPORT\nDRIVER=TELNET\nHTTPPORT='+server.address().port+'\nCMS=1\nUSER=admin,fixture-secret,N0TEST,sysop\nENDPORT\nAPPLICATION 1,BBS,,N0TEST-11,MAIL\n'); await fs.writeFile(path.join(root,'BPQMailChat','BPQMail.cfg'),'BBSForwarding : {}\nBBSUsers : {}'); await fs.writeFile(path.join(dir,'package.json'),' {"type":"module"} ');await fs.writeFile(path.join(dir,'console.config.json'),JSON.stringify({bpqRoot:root,port})); for(const name of await fs.readdir('.'))if(name.endsWith('.mjs')&&!name.includes('.test.')&&name!=='test.mjs')await fs.copyFile(name,path.join(dir,name)); child=spawn(process.execPath,[path.join(dir,'server.mjs')],{cwd:dir,env:{...process.env,BPQ_ROOT:root,BPQ_CONSOLE_CONFIG:path.join(dir,'console.config.json'),BPQ_CONSOLE_PORT:String(port)},windowsHide:true,stdio:['ignore','pipe','pipe']}); await Promise.race([once(child.stdout,'data'),once(child,'exit').then(()=>{throw Error('Fixture server failed');}),new Promise((_,reject)=>{const timer=setTimeout(()=>reject(Error('Fixture timeout')),8000);timer.unref();})]); const base='http://127.0.0.1:'+port,headers={origin:base,'content-type':'application/json'}; const login=await fetch(base+'/api/login',{method:'POST',headers,body:JSON.stringify({user:'admin',password:'fixture-secret'})});const auth=await login.json();headers.cookie=login.headers.get('set-cookie').split(';')[0];headers['x-csrf-token']=auth.csrf; const bytes=[Buffer.from([255,216,255,0,13,10,255]),Buffer.from('Città 📻')],form=new FormData(); for(const [key,value]of Object.entries({to:'RMS/alice@example.test',subject:'Attachment fixture',text:'Hello à',type:'P'}))form.set(key,value); form.append('files',new Blob([bytes[0]]),'image.jpg');form.append('files',new Blob([bytes[1]]),'note.txt');delete headers['content-type']; const created=await fetch(base+'/api/messages',{method:'POST',headers,body:form});assert.equal(created.status,201,await created.clone().text());assert.deepEqual(await created.json(),{id:1,attachmentCount:2});assert.equal(nativePosts,1); assert.equal(b2Body(stored),'Hello à');assert.deepEqual(parseAttachments(stored).map(f=>f.data),bytes); const files=await (await fetch(base+'/api/messages/1/attachments',{headers})).json();assert.equal(files.files.length,2);assert.equal(files.files[0].mime,'image/jpeg');assert.ok(!('data' in files.files[0])); const download=await fetch(base+'/api/messages/1/attachments/0',{headers});assert.match(download.headers.get('content-disposition'),/^attachment/);assert.deepEqual(Buffer.from(await download.arrayBuffer()),bytes[0]); const preview=await fetch(base+'/api/messages/1/attachments/0?preview=1',{headers});assert.equal(preview.headers.get('content-type'),'image/jpeg'); const text=await (await fetch(base+'/api/messages/1/attachments/1?text=1',{headers})).json();assert.equal(text.text,'Città 📻'); const reader=await (await fetch(base+'/api/messages/1',{headers})).json();assert.equal(reader.text,'Hello à'); const inbox=await (await fetch(base+'/api/winlink',{headers})).json();assert.equal(inbox.messages[0].attachmentCount,2);assert.equal(inbox.messages[0].folder,'queue'); const denied=await fetch(base+'/api/messages/1/attachments/0');assert.equal(denied.status,401); const oversized=new FormData();for(const [key,value]of Object.entries({to:'RMS/alice@example.test',subject:'Too big',text:'x'.repeat(30000),type:'P'}))oversized.set(key,value);oversized.append('files',new Blob([Buffer.alloc(60000)]),'large.bin');const rejected=await fetch(base+'/api/messages',{method:'POST',headers,body:oversized});assert.match((await rejected.json()).error,/80 KB/);assert.equal(nativePosts,1); const badHeaders={...headers,'x-csrf-token':'wrong'};assert.equal((await fetch(base+'/api/messages',{method:'POST',headers:badHeaders,body:form})).status,403);assert.equal(nativePosts,1); const deleted=await fetch(base+'/api/messages/1/delete',{method:'POST',headers,body:'{}'});assert.equal(deleted.status,200,await deleted.clone().text());assert.equal((await deleted.json()).ok,true);assert.equal(adminSaves,1); const remaining=await (await fetch(base+'/api/messages',{headers})).json();assert.equal(remaining.length,0); const again=await fetch(base+'/api/messages/1/delete',{method:'POST',headers,body:'{}'});assert.equal((await again.json()).alreadyDeleted,true);assert.equal(adminSaves,1); }finally{if(child&&child.exitCode===null){child.kill();await once(child,'exit');}server.closeAllConnections();await new Promise(resolve=>server.close(resolve));await fs.rm(dir,{recursive:true,force:true});} });