Files
bpq_gui/test.mjs
T

108 lines
25 KiB
JavaScript

import {test} from 'node:test';import assert from 'node:assert/strict';import {parseMessages,parseMessage,parseRoutes,parseRadio} from './bpq.mjs';
import {Chat,parseUser} from './chat.mjs';
import {incoming} from './public/notifications.js';
import {mailDirection,mailFolder,cmsStatus} from './model.mjs';
import {parseAttachments,mimeOf,safeName,b2Body} from './attachments.mjs';
test('B2 body excludes attachment bytes and preserves UTF8',()=>{const body=Buffer.from('Caffè');const b=Buffer.concat([Buffer.from(`Mid: example\r\nBody: ${body.length}\r\nFile: 3 a.bin\r\n\r\n`),body,Buffer.from('\r\nxxx')]);assert.equal(b2Body(b),'Caffè')});
test('B2 attachments preserve binary bytes, byte lengths and multiple files',()=>{const body=Buffer.from('Caffè'),one=Buffer.from([0,255,13,10]),two=Buffer.from('hello');const header=Buffer.from(`Mid: test\r\nBody: ${body.length}\r\nFile: ${one.length} a.bin\r\nFile: ${two.length} notes.txt\r\n\r\n`);const message=Buffer.concat([header,body,Buffer.from('\r\n'),one,Buffer.from('\r\n'),two,Buffer.from('\r\n')]);const files=parseAttachments(message);assert.equal(files.length,2);assert.deepEqual(files[0].data,one);assert.deepEqual(files[1].data,two);assert.equal(files[1].mime,'text/plain');});
test('untrusted HTML/SVG is text and filename paths are removed',()=>{assert.equal(mimeOf(Buffer.from('<svg onload=alert(1)>'),'x.svg'),'text/plain');assert.equal(mimeOf(Buffer.from('<html>'),'x.jpg'),'application/octet-stream');assert.equal(safeName('../../secret.png'),'secret.png');});
test('truncated B2 attachment is rejected, ordinary bulletin has no binary attachments',()=>{assert.throws(()=>parseAttachments(Buffer.from('Body: 1\r\nFile: 999 foo.png\r\n\r\na\r\nxx')));assert.deepEqual(parseAttachments(Buffer.from('R:261013\r\n\r\nBulletin')),[]);});
test('long RMS email route does not drop or shift the message row',()=>{const row='<a href=/WebMail/WM?W123&2482> 2482</a> 13-Oct PN 150 RMS N0TEST@WINLINKN0TEST Queue regression\r\n';const m=parseMessages(row)[0];assert.equal(m.id,2482);assert.equal(m.to,'RMS');assert.equal(m.from,'N0TEST');assert.equal(m.subject,'Queue regression');});
test('own outgoing emails stay in queue even with an SSID or full email sender',()=>{for(const from of ['N0TEST','N0TEST-11','[email protected]']){const m={from,fromAddress:from,to:'RMS',status:'N'};assert.equal(mailDirection(m,'N0TEST'),'outgoing');assert.equal(mailFolder(m,'N0TEST'),'queue')}assert.equal(mailFolder({from:'N0TEST',status:'F'},'N0TEST'),'sent');assert.equal(mailFolder({from:'K1AJD',status:'N'}),'inbox');});
test('CMS clean close is recognized for both directions of FQ',()=>{for(const direction of ['<','>'])assert.equal(cmsStatus(`261013 20:52:23 |RMS Connecting to BBS RMS\n261013 20:52:26 ${direction}RMS FQ\n261013 20:52:28 |RMS RMS Disconnected`).state,'complete');});
test('CMS disconnect alone is neutral, explicit protocol error is an error',()=>{const start='261013 20:52:23 |RMS Connecting to BBS RMS\n';assert.equal(cmsStatus(start+'261013 20:52:28 |RMS RMS Disconnected').state,'ended');assert.equal(cmsStatus(start+'261013 20:52:28 <RMS *** Protocol Error').state,'error');});
test('arrival alerts ignore first load and previously seen IDs',()=>{const messages=[{id:1,type:'B',from:'N1TEST'},{id:2,type:'P',from:'K1AJD'}];assert.deepEqual(incoming(messages,null),{bulletins:[],mail:[]});assert.deepEqual(incoming(messages,new Set([1,2])),{bulletins:[],mail:[]});});
test('arrival alerts distinguish downloaded bulletins and incoming mail, exclude own writes',()=>{const got=incoming([{id:1,type:'B',from:'N1TEST'},{id:2,type:'P',from:'K1AJD'},{id:3,type:'P',from:'N0TEST'}],new Set(),'N0TEST');assert.equal(got.bulletins.length,1);assert.equal(got.mail.length,1);assert.equal(got.mail[0].id,2);});
test('chat roster extracts callsign, name, node, room and idle time',()=>{assert.deepEqual(parseUser('K1AJD at AGCHAT Tony, Augusta, GA [General] Idle for 1279 seconds'),{call:'K1AJD',node:'AGCHAT',name:'Tony',qth:'Augusta, GA',topic:'General',idle:1279});});
test('chat rejects command injection before writing to socket',()=>{const c=new Chat(async()=>({}));c.state='online';assert.throws(()=>c.send('hello\r/QUIT'));assert.throws(()=>c.send('/F'));assert.throws(()=>c.changeTopic('General\r/QUIT'));assert.throws(()=>c.send('hello','K1AJD\rB'));clearInterval(c.timer)});
test('polling roster lines do not become conversation messages',()=>{const c=new Chat(async()=>({}));c.line('1 Station(s) connected:');c.line('N0TEST at CHAT N0TEST, Town Italy [General] Idle for 0 seconds');assert.equal(c.events.length,0);assert.equal(c.users.length,1);clearInterval(c.timer)});
test('fixed-width BPQ list retains empty routing field and decodes subject',()=>{const row='<a href=/WebMail/WM?W123&2444> 2444</a> 13-Oct PF 157 N1TEST N0TEST Test &amp; hello\r\n';assert.deepEqual(parseMessages(row),[{id:2444,date:'13-Oct',type:'P',status:'F',size:157,to:'N1TEST',via:'',from:'N0TEST',subject:'Test & hello'}]);});
test('bulletin columns and routing',()=>{const row='<a href=/WebMail/WM?W123&2466> 2466</a> 13-Oct BN 1784 DX WW HP2DFA DX bulletin\r\n';const m=parseMessages(row)[0];assert.equal(m.to,'DX');assert.equal(m.from,'HP2DFA');assert.equal(m.subject,'DX bulletin');});
test('message content is extracted without executing HTML, CRs normalized',()=>{const m=parseMessage('<textarea id=txt>From: N0TEST\nTo: TEST\nTitle: &lt;script&gt;\n\nhello\rworld &amp; radio</textarea>');assert.equal(m.subject,'<script>');assert.equal(m.text,'hello\nworld & radio');});
test('route status is distinct from last-heard value',()=>{const html='<tr>'+['>4','N1TEST-15','192','6','100','2','0','4','5000','18:10','0','161'].map(c=>'<td>'+c+'</td>').join('')+'</tr>';assert.equal(parseRoutes(html)[0].active,true);assert.equal(parseRoutes(html)[0].nodes,6);});
test('radio online/free/busy are separate states',()=>{const r=parseRadio('Comms State Connected to VARA TNC TNC State Free Mode 2300 Channel State Busy S/N 15,6 Traffic Sent 59 RXed 5480 FT991A 7.050 USB S');assert.equal(r.state,'Free');assert.equal(r.busy,true);assert.equal(r.frequency,'7.050');assert.equal(r.scanning,true)});
test('BPQ monitor decodes fragmented and joined frames, ports and direction', async()=>{
const {MonitorDecoder}=await import('./monitor.mjs');const frames=[],ports=[];const d=new MonitorDecoder(f=>frames.push(f),p=>ports.push(...p));
const definition=Buffer.concat([Buffer.from([255,255]),Buffer.from('3|1 VARA HF|2 Telnet|4 AXIP|')]);
const rx=Buffer.concat([Buffer.from([255,27,17]),Buffer.from('12:00:00R N1TEST-15>NODES Port=4 <UI>\rhello\r'),Buffer.from([254])]);
const tx=Buffer.concat([Buffer.from([255,27,91]),Buffer.from('12:00:01T N0TEST>N1TEST Port=1\rtest\r'),Buffer.from([254])]);
const data=Buffer.concat([Buffer.from('node greeting'),definition,rx,tx]);for(const byte of data)d.push(Buffer.from([byte]));
assert.deepEqual(ports.map(p=>p.id),[1,2,4]);assert.equal(frames.length,2);assert.equal(frames[0].direction,'RX');assert.equal(frames[0].port,4);assert.match(frames[0].text,/hello/);assert.equal(frames[1].direction,'TX');assert.equal(frames[1].port,1);assert.equal(d.buffer.length,0);
});
test('native VARA bitrate keeps TX/RX separate and excludes speed-level number', async()=>{
const {parseVaraRate}=await import('./vara-rate.mjs');assert.deepEqual(parseVaraRate('<134>VARA BITRATE (14) 7050 BPS TX'),{bps:7050,direction:'TX',level:14});assert.deepEqual(parseVaraRate('BITRATE (9) 2682 BPS RX'),{bps:2682,direction:'RX',level:9});assert.deepEqual(parseVaraRate('BITRATE 270 RX'),{bps:270,direction:'RX',level:null});assert.equal(parseVaraRate('BUFFER 7050'),null);assert.equal(parseVaraRate('BITRATE ??? RX'),null);assert.equal(parseVaraRate('BITRATE 999999 BPS TX'),null);
});
test('BPQ message dates preserve UTC hours and infer previous year across January',async()=>{const {bpqTimestamp}=await import('./bpq.mjs');assert.equal(bpqTimestamp('14-Oct 12:11Z',new Date('2026-10-14T12:12:00Z')),'2026-10-14T12:11:00.000Z');assert.equal(bpqTimestamp('31-Dec 23:58Z',new Date('2026-01-01T01:00:00Z')),'2025-12-31T23:58:00.000Z');assert.equal(bpqTimestamp('31-Feb 12:00Z'),null);assert.equal(bpqTimestamp('14-Oct'),null);});
test('generic PACTOR station runs without VARA, chat, monitor or BBS',async()=>{
const fs=await import('node:fs/promises'),os=await import('node:os'),path=await import('node:path'),http=await import('node:http'),cp=await import('node:child_process');
const {parseConfig,publicConfig,loadConfig}=await import('./config.mjs');
const tmp=await fs.mkdtemp(path.join(os.tmpdir(),'bpq-console-test-'));
const upstream=http.createServer((req,res)=>{res.end('BPQ Ports Comms State Connected to PACTOR TNC TNC State Free Mode PACTOR Channel State Clear Traffic Sent 12 RXed 34');});
await new Promise(r=>upstream.listen(0,'127.0.0.1',r));
const httpPort=upstream.address().port;
const cfg=['NODECALL=N9DEMO-7','NODEALIAS=DEMO','LOCATOR=AA00AA','PORT','PORTNUM=3','ID=PACTOR modem','DRIVER=SCSPACTOR','ENDPORT','PORT','PORTNUM=5','DRIVER=TELNET','HTTPPORT='+httpPort,'USER=admin,fixture,N9DEMO,sysop','ENDPORT'].join('\n');
await fs.writeFile(path.join(tmp,'BPQ32.cfg'),cfg);await fs.writeFile(path.join(tmp,'console.config.json'),JSON.stringify({bpqRoot:tmp,httpPort,port:18991}));
const parsed=parseConfig(cfg);assert.equal(parsed.radioPorts[0].id,3);assert.equal(parsed.call,'N9DEMO');
const child=cp.spawn(process.execPath,['server.mjs'],{cwd:process.cwd(),env:{...process.env,BPQ_ROOT:tmp,BPQ_CONSOLE_CONFIG:path.join(tmp,'console.config.json'),BPQ_CONSOLE_PORT:'18991'},windowsHide:true,stdio:['ignore','pipe','pipe']});
try{
await new Promise((resolve,reject)=>{const timeout=setTimeout(()=>reject(new Error('Server fixture timeout')),8000);child.stdout.once('data',()=>{clearTimeout(timeout);resolve()});child.once('exit',code=>{clearTimeout(timeout);reject(new Error('Server fixture exited '+code))})});
const base='http://127.0.0.1:18991';const health=await fetch(base+'/health');assert.equal(health.status,200);assert.equal((await health.json()).service,'bpq-console');const login=await fetch(base+'/api/login',{method:'POST',headers:{Origin:base,'Content-Type':'application/json'},body:JSON.stringify({user:'admin',password:'fixture'})});assert.equal(login.status,200);const user=await login.json();assert.equal(user.call,'N9DEMO');assert.equal(user.config.features.vara,false);assert.equal(user.config.features.bbs,false);assert.equal(user.config.radio.id,3);assert.equal(JSON.stringify(user.config).includes('fixture'),false);
const headers={Cookie:login.headers.get('set-cookie').split(';')[0]};const logbook=await fetch(base+'/api/journal',{headers});assert.equal(logbook.status,200);assert.deepEqual((await logbook.json()).sessions,[]);const denied=await fetch(base+'/api/stations/location',{method:'POST',headers:{...headers,Origin:base,'Content-Type':'application/json'},body:JSON.stringify({call:'N3TEST',locator:'JN45NN'})});assert.equal(denied.status,403);assert.equal((await fetch(base+'/api/terminal',{headers})).status,409);assert.equal((await fetch(base+'/api/chat',{headers})).status,409);assert.equal((await fetch(base+'/api/monitor',{headers})).status,409);assert.equal((await fetch(base+'/api/winlink',{headers})).status,409);
await new Promise(r=>setTimeout(r,1200));const telemetry=await (await fetch(base+'/api/telemetry',{headers})).json();assert.equal(telemetry.current.available,true);assert.equal(telemetry.current.nativeRate.listening,false);assert.equal(telemetry.current.varaCpu,null);assert.equal(telemetry.current.sent,12);
const dash=await (await fetch(base+'/api/dashboard',{headers})).json();assert.equal(dash.counts.messages,0);
}finally{child.kill();await new Promise(r=>child.once('exit',r));await new Promise(r=>upstream.close(r));await fs.rm(tmp,{recursive:true,force:true});}
});
test('generic own-call handling accepts SSIDs without station constants',()=>{assert.equal(mailFolder({from:'N9DEMO-11',status:'N'},'N9DEMO'),'queue');assert.equal(mailFolder({from:'[email protected]',status:'F'},'N9DEMO'),'sent');assert.equal(mailFolder({from:'N1OTHER',status:'N'},'N9DEMO'),'inbox');});
test('configuration detects a Telnet-only node without inventing a modem',async()=>{const {parseConfig}=await import('./config.mjs');const c=parseConfig('NODECALL=N8TEST-7\nPORT\nDRIVER=Telnet.dll\nPORTNUM=2\nHTTPPORT=8088\nTCPPORT=9000\nENDPORT');assert.equal(c.httpPort,8088);assert.equal(c.telnetPort,9000);assert.deepEqual(c.radioPorts,[]);assert.equal(c.call,'N8TEST');});
test('empty modem state after restart remains idle',()=>{assert.equal(parseRadio('Comms State Connected to VARA TNC TNC State Mode Channel State Clear').state,'Free');});
test('journal locator conversion validates grid precision and distance',async()=>{const {locatorPosition,distanceKm}=await import('./journal.mjs');const a=locatorPosition('JN45NN');assert.ok(Math.abs(a.lat-45.56)<.03);assert.ok(Math.abs(a.lon-9.12)<.05);assert.equal(locatorPosition('ZZ99ZZ'),null);assert.equal(locatorPosition('JN45NN00').locator,'JN45NN00');assert.equal(distanceKm(a,a),0);assert.ok(distanceKm(a,locatorPosition('IM75IV'))>1500);});
test('journal merges VARA traffic and BBS messages without duplicating session',async()=>{const {parseVaraLog,parseBbsLog,mergeSessions}=await import('./journal.mjs');const radio=parseVaraLog('2026-10-15 12:00:00 ->CONNECT N0TEST-11 N1TEST-8\n2026-10-15 12:00:10 <-CONNECTED N0TEST-11 N1TEST-8 2300\n2026-10-15 12:01:00 N1TEST-8 Average S/N: 12,3 dB\n2026-10-15 12:01:00 Disconnected TX: 127 Bytes (Max: 270 bps) RX: 3180 Bytes (Max: 500 bps)');const bbs=parseBbsLog('261015 12:00:00 |N1TEST Connecting to BBS N1TEST\n261015 12:00:00 >N1TEST ATTACH 3\n261015 12:00:00 >N1TEST RADIO 14.100 USB\n261015 12:00:30 |N1TEST Uncompressing Message Comp Len 300 Msg Len 800 CRC abcd\n261015 12:00:31 ?N1TEST Msg 20 Routing Trace To WX Via WW\n261015 12:00:59 <N1TEST FQ\n261015 12:01:00 |N1TEST N1TEST Disconnected');const out=mergeSessions(bbs,radio,[]);assert.equal(out.length,1);assert.equal(out[0].service,'BBS');assert.equal(out[0].status,'complete');assert.equal(out[0].txBytes,127);assert.equal(out[0].rxBytes,3180);assert.equal(out[0].receivedMessages,1);assert.equal(out[0].messages[0].id,20);assert.equal(out[0].duration,50);assert.equal(out[0].frequency,14.1);assert.equal(out[0].port,3);assert.equal(out[0].snr,12.3);});
test('journal recognizes incoming Winlink and keeps CMS counters separate',async()=>{const {parseVaraLog,parseCmsLog,mergeSessions}=await import('./journal.mjs');const radio=parseVaraLog('2026-10-15 12:00:00 Incoming connection...\n2026-10-15 12:00:05 N2TEST connected VARA HF v4.9.0\n2026-10-15 12:01:00 Disconnected TX: 100 Bytes (Max: 270 bps) RX: 200 Bytes (Max: 270 bps)','VARA','N0TEST');const cms=parseCmsLog('12:00:10 15 N2TEST Connected to CMS\n12:00:59 15 Disconnected. Bytes Sent = 80 Bytes Received 50 Time 49 Seconds','2026-10-15','N0TEST');const list=mergeSessions([],radio,cms);assert.equal(list.length,1);assert.equal(list[0].service,'Winlink');assert.equal(list[0].direction,'incoming');assert.equal(list[0].txBytes,100);assert.equal(list[0].cmsTraffic.txBytes,80);});
test('journal never exposes credentials or mail/chat text from raw logs',async()=>{const {parseBbsLog,parseCmsLog}=await import('./journal.mjs');const log='261015 12:00:00 |RMS Connecting to BBS RMS\n261015 12:00:01 >RMS ;PR: secret-fixture\n261015 12:00:02 <RMS private-message-fixture\n261015 12:00:04 |RMS RMS Disconnected';const out=JSON.stringify(parseBbsLog(log));assert.equal(out.includes('secret-fixture'),false);assert.equal(out.includes('private-message-fixture'),false);const cms=parseCmsLog('23:59:00 15 N0TEST-11 Connected to CMS\n23:59:20 15 Disconnected. Bytes Sent = 12 Bytes Received 13 Time 20 Seconds','2026-10-15','N0TEST');assert.equal(cms[0].call,'CMS');assert.equal(cms[0].transport,'Internet');assert.equal(cms[0].endedAt,'2026-10-15T23:59:20Z');});
test('journal keeps simultaneous rejected inbound and successful outbound calls separate',async()=>{const {parseVaraLog,parseBbsLog,mergeSessions}=await import('./journal.mjs');const radio=parseVaraLog('2026-10-15 12:00:02 ->CONNECT N0TEST-11 N1TEST-8\n2026-10-15 12:00:20 <-CONNECTED N0TEST-11 N1TEST-8 2300\n2026-10-15 12:01:00 Disconnected TX: 10 Bytes (Max: 270 bps) RX: 20 Bytes (Max: 270 bps)');const bbs=parseBbsLog('261015 12:00:00 |N1TEST Connecting to BBS N1TEST\n261015 12:00:02 |N1TEST-8 Incoming Connect from N1TEST\n261015 12:00:03 >N1TEST-8 Already Connected\n261015 12:00:04 |N1TEST-8 N1TEST-8 Disconnected\n261015 12:00:20 <N1TEST *** Connected to N1TEST-8\n261015 12:00:59 <N1TEST FQ\n261015 12:01:00 |N1TEST N1TEST Disconnected');const list=mergeSessions(bbs,radio,[]);assert.equal(list.length,2);assert.equal(list.find(s=>s.direction==='incoming').status,'failed');assert.equal(list.find(s=>s.direction==='outgoing').txBytes,10);assert.equal(list.find(s=>s.direction==='outgoing').status,'complete');});
test('journal saves locators only for observed stations and validates input',async()=>{const {Journal}=await import('./journal.mjs');const fs=await import('node:fs/promises'),path=await import('node:path'),os=await import('node:os');const tmp=await fs.mkdtemp(path.join(os.tmpdir(),'bpq-journal-test-'));try{await fs.mkdir(path.join(tmp,'Logs'));const now=new Date(),date=now.toISOString().slice(0,10).replaceAll('-','');await fs.writeFile(path.join(tmp,'Logs','CMSAccess_'+date+'.log'),'12:00:00 15 N3TEST Connected to CMS\n12:01:00 15 Disconnected. Bytes Sent = 1 Bytes Received 2 Time 60 Seconds');const j=new Journal({root:tmp,sysop:{call:'N0TEST'},nodeCall:'N0TEST-7',locator:'JN45NN'},tmp);await assert.rejects(j.saveLocation('N3TEST','ZZ99ZZ'));await assert.rejects(j.saveLocation('N4OTHER','JN45NN'));const d=await j.saveLocation('N3TEST','JN46LB');assert.equal(d.stations[0].position.locator,'JN46LB');assert.ok(d.stations[0].distance>0);assert.equal(JSON.parse(await fs.readFile(path.join(tmp,'station-locations.json'),'utf8')).N3TEST.locator,'JN46LB');}finally{await fs.rm(tmp,{recursive:true,force:true})}});
test('journal identifies Telnet access without exposing credentials or IP addresses',async()=>{const {parseTelnetLog,classifyTransport}=await import('./journal.mjs');const rows=parseTelnetLog('16/10/2026 12:00:00 1 127.0.0.1 Incoming Connect on Port 8100\n16/10/2026 12:00:01 1 127.0.0.1 Call Accepted Callsign=N0TEST\n16/10/2026 12:00:02 1 127.0.0.1 password=secret-fixture','Telnet_261016.log');assert.equal(rows.length,1);assert.equal(rows[0].local,true);assert.equal(rows[0].port,8100);assert.equal(JSON.stringify(rows).includes('secret-fixture'),false);assert.equal(JSON.stringify(rows).includes('127.0.0.1'),false);const s=classifyTransport({call:'N0TEST-12',startedAt:rows[0].at,service:'Chat',transport:'Unknown',sources:[]},{ports:[]},rows);assert.equal(s.transport,'Local');assert.ok(s.sources.includes('Telnet_261016.log'));});
test('journal classifies explicit BPQ ports and keeps historical missing ports honest',async()=>{const {classifyTransport}=await import('./journal.mjs');const config={ports:[{id:1,driver:'SCSPACTOR'},{id:2,driver:'TELNET'},{id:4,driver:'BPQAXIP'}]};for(const [port,expected]of [[1,'Radio'],[2,'Internet'],[4,'NET/ROM']])assert.equal(classifyTransport({port,transport:'Unknown',sources:[]},config).transport,expected);const cms=classifyTransport({call:'N2TEST',service:'Winlink',transport:'Unknown',sources:[]},config);assert.equal(cms.transport,'CMS');assert.match(cms.transportEvidence,/non è archiviato/);const bbs=classifyTransport({call:'N2TEST',service:'BBS',transport:'Unknown',sources:[]},config);assert.equal(bbs.transport,'BPQ');assert.match(bbs.transportEvidence,/porta di ingresso non è archiviata/);});
test('journal parses CONNECT with a numbered port',async()=>{const {parseBbsLog,classifyTransport}=await import('./journal.mjs');const s=parseBbsLog('261016 12:00:00 |N2TEST Connecting to BBS N2TEST\n261016 12:00:01 >N2TEST C 4 N2TEST-11\n261016 12:00:20 |N2TEST N2TEST Disconnected')[0];assert.equal(s.port,4);assert.equal(classifyTransport(s,{ports:[{id:4,driver:'BPQAXIP'}]}).transport,'NET/ROM');});
// Small protocol fixture: standard JFIF header bytes, not a stored BBS image.
const sevenLineHex='7aaef5f9aec026218ba6d09e5830c53c52502521ce9eb22729adfa2be17d7029352324265cc8ec23b66436239e315058cdfa2158bdb8418ea16c4f72b2c6d046b84921987b';
const sevenDecodedHex='ffd8ffe000104a46494600010101006000600000ffdb00430006040506050406060506070706080a100a0a09090a140e0f0c1017141818171416161a1d25';
const sevenHeaders=['20676f5f372b2e20303031206f6620303032205041594c4f41442e42494e2030303030313030203030343020303031202837504c55532076322e31292020b0b1b2db4d9b97','20676f5f372b2e20303032206f6620303032205041594c4f41442e42494e2030303030313030203030343020303031202837504c55532076322e31292020b0b1b2dbb04996'];
const sevenFooters=['2073746f705f372b2e20285041594c4f41442e5030312f303229205b31323334353637385d20202020202020202020202020202020202020202020202020b0b1b2db588db4','2073746f705f372b2e20285041594c4f41442e5030322f303229205b31323334353637385d20202020202020202020202020202020202020202020202020b0b1b2dbdd8925'];
function sevenFixture(part,sender='N0TEST'){return Buffer.concat([Buffer.from('From: '+sender+'\r\n\r\n'),Buffer.from(sevenHeaders[part-1],'hex'),Buffer.from('\r\n'),Buffer.from(sevenLineHex,'hex'),Buffer.from('\r\n'),Buffer.from(sevenFooters[part-1],'hex'),Buffer.from('\r\n')]);}
test('7plus decodes a known binary line and verifies both CRC fields',async()=>{const {decodeSevenLine}=await import('./sevenplus.mjs');const line=Buffer.from(sevenLineHex,'hex'),result=decodeSevenLine(line);assert.equal(result.number,0);assert.equal(result.data.toString('hex'),sevenDecodedHex);for(const at of [0,64,67]){const damaged=Buffer.from(line);damaged[at]^=1;assert.throws(()=>decodeSevenLine(damaged));}assert.throws(()=>decodeSevenLine(line.subarray(0,68)));});
test('7plus combines out-of-order parts and refuses incomplete or damaged groups',async()=>{const {scanSevenPlus,assembleSevenPlus}=await import('./sevenplus.mjs');const first=scanSevenPlus(sevenFixture(1),1),second=scanSevenPlus(sevenFixture(2),2);assert.equal(first[0].issue,null);assert.equal(second[0].issue,null);const incomplete=assembleSevenPlus(first);assert.equal(incomplete.metadata.state,'incomplete');assert.deepEqual(incomplete.metadata.missingParts,[2]);assert.equal(incomplete.file,null);const done=assembleSevenPlus([...second,...first]);assert.equal(done.metadata.state,'complete');assert.equal(done.file.size,100);assert.deepEqual(done.file.data,Buffer.concat([Buffer.from(sevenDecodedHex,'hex'),Buffer.from(sevenDecodedHex,'hex')]).subarray(0,100));const damaged=sevenFixture(2);damaged[damaged.indexOf(Buffer.from(sevenLineHex,'hex'))]^=1;const failed=assembleSevenPlus([...first,...scanSevenPlus(damaged,2)]);assert.equal(failed.metadata.state,'damaged');assert.deepEqual(failed.metadata.damagedParts,[2]);assert.equal(failed.file,null);});
test('7plus isolates senders and rejects unsafe metadata before allocating data',async()=>{const {scanSevenPlus,assembleSevenPlus}=await import('./sevenplus.mjs');const a=scanSevenPlus(sevenFixture(1,'N0TEST'),1),b=scanSevenPlus(sevenFixture(2,'N1OTHER'),2);assert.notEqual(a[0].key,b[0].key);assert.equal(assembleSevenPlus([...a,...b]).file,null);const bad={...a[0],total:999999999,size:1e15};assert.equal(assembleSevenPlus([bad]).metadata.state,'damaged');const damagedHeader=sevenFixture(1);damagedHeader[damagedHeader.indexOf(Buffer.from('PAYLOAD.BIN'))]^=1;assert.ok(scanSevenPlus(damagedHeader,1)[0].issue);});
test('7plus includes only currently visible messages and invalidates a removed part',async()=>{const {SevenPlus}=await import('./sevenplus.mjs');const fs=await import('node:fs/promises'),path=await import('node:path'),os=await import('node:os');const tmp=await fs.mkdtemp(path.join(os.tmpdir(),'bpq-sevenplus-test-'));try{await fs.mkdir(path.join(tmp,'BPQMailChat','Mail'),{recursive:true});await fs.writeFile(path.join(tmp,'BPQMailChat','Mail','m_000001.mes'),sevenFixture(1));await fs.writeFile(path.join(tmp,'BPQMailChat','Mail','m_000002.mes'),sevenFixture(2));const codec=new SevenPlus(tmp);const first=await codec.forMessage(1,[{id:1}]);assert.equal(first.file,null);const full=await codec.forMessage(1,[{id:1},{id:2}]);assert.equal(full.file.size,100);const hidden=await codec.forMessage(1,[{id:1}]);assert.equal(hidden.file,null);assert.equal(hidden.metadata.state,'incomplete');}finally{await fs.rm(tmp,{recursive:true,force:true})}});
test('idle chat links stay in the roster, without conversation messages',()=>{
const c=new Chat(async()=>({}));
try {
for(let i=0;i<2;i++){
c.line('Links Defined:');c.line('HB9ON-2 Idle');c.line('IW2OHX-5 Open RTT 1');c.line('N0TEST Connecting');
assert.deepEqual(c.links,[{call:'HB9ON-2',state:'Idle',detail:''},{call:'IW2OHX-5',state:'Open',detail:'RTT 1'},{call:'N0TEST',state:'Connecting',detail:''}]);
assert.equal(c.events.length,0);
}
c.line('K1ABC I am idle today');
assert.equal(c.events.at(-1).text,'I am idle today');
assert.equal(c.events.at(-1).type,'message');
} finally {clearInterval(c.timer);}
});