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 {parseConfig,validateSysopUsers,authenticateSysop} from './config.mjs'; const accountLines='USER=admin,primary-secret,N0TEST,SYSOP\nUSER=Marco,secondary-secret,N0OTHER,SYSOP\nUSER=guest,guest-secret,N0GUEST,\n'; const users=parseConfig(accountLines).users; test('all native SYSOP accounts can log in with their own identity; normal users and wrong passwords cannot',()=>{ assert.deepEqual(authenticateSysop(users,'ADMIN','primary-secret'),{name:'admin',call:'N0TEST'}); assert.deepEqual(authenticateSysop(users,'marco','secondary-secret'),{name:'Marco',call:'N0OTHER'}); for(const [name,password]of [['guest','guest-secret'],['Marco','SECONDARY-SECRET'],['missing','primary-secret']])assert.equal(authenticateSysop(users,name,password),null); }); test('optional sysopUsers restricts native SYSOP access case-insensitively and cannot grant normal users access',()=>{ const allow=validateSysopUsers(['mArCo','MARCO'],users);assert.deepEqual(allow,['mArCo']); assert.deepEqual(authenticateSysop(users,'Marco','secondary-secret',allow),{name:'Marco',call:'N0OTHER'}); assert.equal(authenticateSysop(users,'admin','primary-secret',allow),null); assert.equal(authenticateSysop(users,'Marco','secondary-secret',[]),null); assert.equal(validateSysopUsers(undefined,users),undefined); for(const bad of [null,'Marco',{},[''],[12],['guest'],['missing']])assert.throws(()=>validateSysopUsers(bad,users),/sysopUsers/); }); const listen=server=>new Promise(resolve=>server.listen(0,'127.0.0.1',resolve)); test('HTTP sessions isolate multiple sysops, retain station identity, enforce the allow-list and reread native roles',async()=>{ const dir=await fs.mkdtemp(path.join(os.tmpdir(),'bpq-multi-sysop-')),root=path.join(dir,'station'); let child; const upstream=http.createServer((req,res)=>res.end('BPQ Ports')); const stop=async()=>{if(child&&child.exitCode===null){child.kill();await once(child,'exit');}child=null;}; try{ await fs.mkdir(root);await listen(upstream); const native='NODECALL=N0TEST-7\nPORT\nDRIVER=TELNET\nHTTPPORT='+upstream.address().port+'\n'+accountLines+'ENDPORT\n'; await fs.writeFile(path.join(root,'BPQ32.cfg'),native); await fs.writeFile(path.join(dir,'package.json'),' {"type":"module"} '); for(const name of await fs.readdir('.'))if(name.endsWith('.mjs')&&!name.endsWith('.test.mjs')&&name!=='test.mjs')await fs.copyFile(name,path.join(dir,name)); const start=async extra=>{ const probe=net.createServer();await listen(probe);const port=probe.address().port;await new Promise(resolve=>probe.close(resolve)); await fs.writeFile(path.join(dir,'console.config.json'),JSON.stringify({bpqRoot:root,port,sysopUser:'admin',...extra})); 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']}); let timer;try{await Promise.race([once(child.stdout,'data'),once(child,'exit').then(()=>{throw Error('Fixture server failed');}),new Promise((_,reject)=>{timer=setTimeout(()=>reject(Error('Fixture startup timeout')),8000);})]);}finally{clearTimeout(timer);} const base='http://127.0.0.1:'+port; return {base,login:(user,password)=>fetch(base+'/api/login',{method:'POST',headers:{origin:base,'content-type':'application/json'},body:JSON.stringify({user,password})})}; }; let client=await start({}); const primaryResponse=await client.login('admin','primary-secret'),secondaryResponse=await client.login('MARCO','secondary-secret'); assert.equal(primaryResponse.status,200);assert.equal(secondaryResponse.status,200); const primary=await primaryResponse.json(),secondary=await secondaryResponse.json(); assert.equal(primary.call,'N0TEST');assert.equal(secondary.call,'N0OTHER');assert.equal(secondary.name,'Marco'); assert.equal(secondary.config.call,'N0TEST');assert.equal(secondary.config.nodeCall,'N0TEST-7'); assert.notEqual(primary.csrf,secondary.csrf);assert.ok(!JSON.stringify(secondary).includes('secret'));assert.ok(!('sysopUsers' in secondary.config)); const primaryCookie=primaryResponse.headers.get('set-cookie').split(';')[0],secondaryCookie=secondaryResponse.headers.get('set-cookie').split(';')[0]; assert.notEqual(primaryCookie,secondaryCookie); const session=async cookie=>fetch(client.base+'/api/session',{headers:{cookie}}); assert.equal((await (await session(primaryCookie)).json()).call,'N0TEST'); assert.equal((await (await session(secondaryCookie)).json()).call,'N0OTHER'); const logout=csrf=>fetch(client.base+'/api/logout',{method:'POST',headers:{origin:client.base,cookie:secondaryCookie,'x-csrf-token':csrf}}); assert.equal((await logout(primary.csrf)).status,403);assert.equal((await session(secondaryCookie)).status,200); assert.equal((await logout(secondary.csrf)).status,200);assert.equal((await session(secondaryCookie)).status,401);assert.equal((await session(primaryCookie)).status,200); assert.equal((await client.login('guest','guest-secret')).status,401);assert.equal((await client.login('Marco','wrong')).status,401); await stop();client=await start({sysopUsers:['MARCO']}); assert.equal((await client.login('admin','primary-secret')).status,401); assert.equal((await client.login('Marco','secondary-secret')).status,200); await fs.writeFile(path.join(root,'BPQ32.cfg'),native.replace('N0OTHER,SYSOP','N0OTHER,')); assert.equal((await client.login('Marco','secondary-secret')).status,401); }finally{ await stop();upstream.closeAllConnections();await new Promise(resolve=>upstream.close(resolve)); assert.ok(path.resolve(dir).startsWith(path.resolve(os.tmpdir())+path.sep));await fs.rm(dir,{recursive:true,force:true}); } });