Files
bpq_gui/server.mjs
T
alberto c98c67e18b Add detached service windows and selectable terminal themes
Support standalone APRS, Monitor, Chat and Terminal views with courtesy screens, window focus and return controls, shared sessions and suspended embedded polling.

Add five persistent phosphor palettes, remove Console terminal idle disconnections, and display decoded Mic-E movement and altitude with expandable original packets.

Document the new behavior and add regression coverage. Validation: 182 tests passed; the known hanging PowerShell startup readiness test was excluded.
2026-10-19 22:15:15 +02:00

217 lines
36 KiB
JavaScript

import {MessageReadState} from './message-read-state.mjs';
import {ForwardingScheduler} from './forwarding-scheduler.mjs';
import {deleteNativeMessage} from './delete-message.mjs';
import {readSubmission,outgoingForm,verifySavedAttachments,uploadLimits} from './mail-upload.mjs';
import {SyncOperations} from './sync-operations.mjs';
import {RadioControl} from './radio-control.mjs';
import {RadioPorts} from './radio-ports.mjs';
import {AprsSettings} from './aprs-settings.mjs';
import {reconfigureAprs} from './aprs-native.mjs';
import {AprsActivity} from './aprs-activity.mjs';
import {Terminal} from './terminal.mjs';
import {SingleFlight} from './single-flight.mjs';
import {ProgressiveMetadata} from './progressive-metadata.mjs';
import http from 'node:http';
import {Journal} from './journal.mjs';
import {GatewayDirectory,modemFamily,packetPort} from './winlink-gateways.mjs';
import {WinlinkRadio} from './winlink-radio.mjs';
import {ManualForwarding} from './manual-forwarding.mjs';
import {forwardingHistory} from './forwarding.mjs';
import {Forwarding} from './forwarding.mjs';
import {SevenPlus} from './sevenplus.mjs';
import {loadConfig,parseConfig,publicConfig,ownCall,authenticateSysop} from './config.mjs';
import {readFile, stat,open} from 'node:fs/promises';
import path from 'node:path';
import {fileURLToPath} from 'node:url';
import {randomBytes,timingSafeEqual} from 'node:crypto';
import {decode,plain,parseMessages,parseRoutes,parseMessage,parseRadio,bpqTimestamp} from './bpq.mjs';
import {Chat} from './chat.mjs';
import {Monitor} from './monitor.mjs';
import {VaraRate} from './vara-rate.mjs';
import {mailDirection,mailFolder,cmsStatus} from './model.mjs';
import os from 'node:os';
import {execFile} from 'node:child_process';
import {parseAttachments,safeName,b2Body,attachmentSummary} from './attachments.mjs';
const dir=path.dirname(fileURLToPath(import.meta.url));
const config=await loadConfig();
const root=config.root;
const messageReadState=new MessageReadState(path.join(dir,'message-read-state.json'));await messageReadState.ready;
const radioControl=new RadioControl(config);await radioControl.snapshot();
setInterval(()=>radioControl.snapshot().catch(()=>{}),2000).unref();
const journal=new Journal(config,dir);
const sevenPlus=new SevenPlus(root);
const upstream='http://127.0.0.1:'+config.httpPort;
const sessions=new Map(), attempts=new Map();
const port=config.port;
const credentials=async()=>{const found=parseConfig(await readFile(path.join(root,'BPQ32.cfg'),'utf8')).users.find(u=>u.user===config.sysop.user);if(!found)throw new Error('Account sysop configurato non trovato');return found;};
const chat=new Chat(credentials,{port:config.telnetPort,call:config.sysop.call,alias:config.alias,...config.telnetPrompts});
const monitor=new Monitor(credentials,{port:config.monitorPort});
const varaRate=config.features.vara?new VaraRate(config.varaSyslogPort||18514):null;
let telemetry={current:null,history:[]},telemetryBusy=false,priorTraffic=null,priorCpu=null,varaCpu=null,priorVaraCpu=null;
function cpuSample(){const totals=os.cpus().reduce((a,c)=>({idle:a.idle+c.times.idle,total:a.total+Object.values(c.times).reduce((x,y)=>x+y,0)}),{idle:0,total:0});const result=priorCpu?Math.max(0,Math.min(100,100*(1-(totals.idle-priorCpu.idle)/(totals.total-priorCpu.total||1)))):null;priorCpu=totals;return result;}
function varaCpuSample(){execFile('powershell.exe',['-NoProfile','-NonInteractive','-Command',"$p=Get-Process -Name VARA -ErrorAction SilentlyContinue;if($p){$p|ForEach-Object {$_.TotalProcessorTime.TotalMilliseconds}|ConvertTo-Json -Compress}"],{windowsHide:true,timeout:5000},(err,out)=>{try{const value=JSON.parse(out);const ms=Array.isArray(value)?value.reduce((a,b)=>a+b,0):value;const now=Date.now();varaCpu=priorVaraCpu&&ms>=priorVaraCpu.ms?Math.min(100,Math.max(0,(ms-priorVaraCpu.ms)/(now-priorVaraCpu.at)/os.cpus().length*100)):null;priorVaraCpu={ms,at:now};}catch{varaCpu=null;priorVaraCpu=null;}});}
async function sampleTelemetry(){if(telemetryBusy)return;telemetryBusy=true;try{const html=config.radio?await bpq('/Node/Port?'+config.radio.id):'';const radio=parseRadio(html||'');const now=Date.now();const active=radio.connected&&!/^(Free|Idle)$/i.test(radio.state)&&Boolean(radio.state.trim());const connecting=/connect|call/i.test(radio.state)&&!/connected/i.test(radio.state);const connections=[...plain(html||'').matchAll(/\bCONNECTED ([A-Z0-9]+(?:-\d+)?) ([A-Z0-9]+(?:-\d+)?) (\d+)/g)];const calls=connections.at(-1);const delta=priorTraffic?(now-priorTraffic.at)/1000:0;const txBps=delta&&radio.sent>=priorTraffic.sent?8*(radio.sent-priorTraffic.sent)/delta:0;const rxBps=delta&&radio.received>=priorTraffic.received?8*(radio.received-priorTraffic.received)/delta:0;const sn=Number(String(radio.snr).replace(',','.'));const nativeRate=varaRate?.snapshot(active&&!connecting)||{listening:false,bps:null,tx:null,rx:null};const sample={at:now,available:!!config.radio,active,connecting,nativeRate,varaTxBps:nativeRate.tx,varaRxBps:nativeRate.rx,varaBps:nativeRate.bps,state:radio.state,frequency:radio.frequency,scan:radio.scanning,busy:radio.busy,txBps,rxBps,cpu:cpuSample(),varaCpu,snr:active&&Number.isFinite(sn)?sn:null,lastSnr:Number.isFinite(sn)?sn:null,caller:active&&!connecting&&calls?calls[1]:null,called:active&&!connecting&&calls?calls[2]:null,sent:radio.sent,received:radio.received};priorTraffic={at:now,sent:radio.sent,received:radio.received};telemetry.current=sample;telemetry.history.push(sample);if(telemetry.history.length>180)telemetry.history.shift();}catch(e){telemetry.current={at:Date.now(),available:false,error:'Modem non disponibile',cpu:cpuSample(),varaCpu};priorTraffic=null;}finally{telemetryBusy=false;}}
setInterval(sampleTelemetry,2000).unref();if(config.features.vara)setInterval(varaCpuSample,5000).unref();setTimeout(()=>{sampleTelemetry();if(config.features.vara)varaCpuSample()},1000).unref();
let upstreamQueue=Promise.resolve(), mailKey=null, mailKeyAt=0;
const mailReads=new SingleFlight(),metadataReads=new SingleFlight();
function bpq(url,options={}){const work=upstreamQueue.then(()=>bpqRequest(url,options));upstreamQueue=work.catch(()=>{});return work;}
async function bpqRequest(url, options={}) {
// BPQ's legacy HTTP server is compatible with plain HTTP requests; modern
// fetch headers can make its local-auth detection fall back to the signon page.
let payload=options.body,headers={Connection:'close'};
if(payload instanceof FormData){const encoded=new Request(upstream+url,{method:'POST',body:payload});headers['Content-Type']=encoded.headers.get('content-type');payload=Buffer.from(await encoded.arrayBuffer());if(payload.length>96000)throw Error('Messaggio troppo grande per il server HTTP BPQ');}
if(payload){payload=Buffer.from(payload);headers['Content-Length']=payload.length;}
return new Promise((resolve,reject)=>{const request=http.request(upstream+url,{method:options.method||'GET',headers,agent:false},response=>{let chunks=[];response.on('data',c=>chunks.push(c));response.on('end',()=>{if(response.statusCode!==200)return reject(new Error('BPQ non risponde ('+response.statusCode+')'));resolve(Buffer.concat(chunks).toString('utf8'))});response.on('error',reject)});request.setTimeout(10000,()=>request.destroy(new Error('Timeout BPQ')));request.on('error',reject);if(payload)request.write(payload);request.end()});
}
function mailContext(){return mailReads.run('context',async()=>{if(mailKey&&Date.now()-mailKeyAt<1800000)return {key:mailKey};const html=await bpq('/Webmail');const key=html.match(/WMB\?([^>\s]+)/)?.[1];if(!key)throw new Error('WebMail BPQ non disponibile');mailKey=key;mailKeyAt=Date.now();return {html,key};});}
function messages(includeTimes=true){return mailReads.run(includeTimes?'full':'quick',()=>readMessages(includeTimes));}
async function readMessages(includeTimes=true){let {key}=await mailContext();let html=await bpq('/WebMail/WMALL?'+key);if(!html.includes('Message List')){mailKey=null;({key}=await mailContext());html=await bpq('/WebMail/WMALL?'+key);if(!html.includes('Message List'))throw new Error('Lista messaggi BPQ non disponibile');}const list=parseMessages(html).filter(m=>m.status!=='K');if(includeTimes)return messageMetadata.enrich(list);for(const m of list.filter(m=>m.type==='P'&&(m.to==='RMS'||m.needsMetadata))){const f=await messageFields(m.id);m.from=f.From||m.from;m.to=f.To||m.to;m.subject=f.Title||m.subject;m.via=f.VIA||m.via;}return list;}
function equal(a,b){const aa=Buffer.from(a),bb=Buffer.from(b);return aa.length===bb.length&&timingSafeEqual(aa,bb);}
async function authenticate(user,password){const users=parseConfig(await readFile(path.join(root,'BPQ32.cfg'),'utf8')).users;const identity=authenticateSysop(users,user,password,config.sysopUsers);return identity?{...identity,config:publicConfig(config)}:null;}
async function body(req){let chunks=[],size=0;for await(const chunk of req){size+=chunk.length;if(size>70000)throw new Error('Messaggio troppo grande');chunks.push(chunk)}return JSON.parse(Buffer.concat(chunks).toString()||'{}');}
function json(res,status,data){res.writeHead(status,{'Content-Type':'application/json; charset=utf-8','Cache-Control':'no-store'});res.end(JSON.stringify(data));}
function session(req){const token=req.headers.cookie?.match(/(?:^|;\s*)alnode=([a-f0-9]+)/)?.[1];const s=sessions.get(token);if(s&&s.expires>Date.now()){s.expires=Date.now()+8*3600000;return s;}if(token){s?.terminal?.close();sessions.delete(token);}return null;}
async function dashboard(){
const jobs=await Promise.allSettled([config.radio?bpq('/Node/Port?'+config.radio.id):Promise.resolve(null),bpq('/Node/Routes.html'),bpq('/Node/Nodes.html'),config.features.bbs?messages(false):Promise.resolve([])]);
const val=i=>jobs[i].status==='fulfilled'?jobs[i].value:null;
const list=val(3)||[];let activity=[],sync=null,cms=[];
try{const date=new Date().toLocaleDateString('sv-SE',{timeZone:'UTC'}).replaceAll('-','').slice(2);const log=await readFile(path.join(root,'Logs',`log_${date}_BBS.txt`),'utf8');
const lines=log.split(/\r?\n/);const relevant=lines.filter(l=>/Connecting to BBS|Incoming Connect|Uncompressing Message|Failure with|Disconnected/.test(l)&&!/[;](PR|PQ|FW):/.test(l));
activity=relevant.slice(-12).reverse().map(l=>({at:l.slice(0,15),text:l.slice(16).replace(/^[|<>?!][^ ]+\s*/, '')}));
const finish=lines.findLastIndex(l=>/[<>][A-Z0-9-]+\s+FQ/.test(l));if(finish>=0){let start=finish;while(start>0&&!/Connecting to BBS|Incoming Connect/.test(lines[start]))start--;const count=lines.slice(start,finish).filter(l=>/Uncompressing Message/.test(l)).length;sync={at:lines[finish].slice(0,15),received:count};}
const cmsLog=await readFile(path.join(root,'Logs',`CMSAccess_20${date}.log`),'utf8').catch(()=> '');cms=cmsLog.split(/\r?\n/).filter(l=>/Connected to CMS/.test(l)&&!l.includes((config.apps.find(a=>a.command==='BBS')?.call||'!')+' ')).map(l=>({at:l.slice(0,8),call:l.match(/\d+\s+(\S+) Connected/)?.[1]}));
}catch{}
const nodes=val(2)?[...plain(val(2)).matchAll(/\b([A-Z0-9]{1,6}:[A-Z0-9]+(?:-\d+)?)\b/g)].map(m=>m[1]):[];
return {updatedAt:new Date().toISOString(),radio:val(0)?parseRadio(val(0)):null,routes:val(1)?parseRoutes(val(1)):[],nodes:[...new Set(nodes)],counts:{messages:list.length,bulletins:list.filter(m=>m.type==='B').length,personal:list.filter(m=>m.type==='P').length},recent:list.slice(0,5),activity,sync,cms,errors:jobs.flatMap((r,i)=>r.status==='rejected'?[['Radio','Rete','Nodi','BBS'][i]+': '+r.reason.message]:[])};
}
let lastCmsRequest=0;
const radioPorts=new RadioPorts(config,radioControl,bpq,()=>telemetry);
const aprsSettings=new AprsSettings(config,radioPorts,()=>reconfigureAprs(credentials,config));
const aprsActivity=new AprsActivity(config,dir,bpq,credentials,aprsSettings);
setInterval(()=>radioPorts.sample().catch(()=>{}),2500).unref();
const forwarding=new Forwarding(config,bpq,()=>({...telemetry.current,txSuspended:radioControl.txSuspended,portSuspended:radioPorts.paused(config.radio?.id),portsPaused:Object.fromEntries(config.radioPorts.map(p=>[p.id,radioPorts.paused(p.id)])),active:radioControl.blocked||radioControl.txSuspended||radioPorts.paused(config.radio?.id)||telemetry.current?.active}));
const gatewayDirectory=new GatewayDirectory(config,dir);
const winlinkRadio=new WinlinkRadio(config,dir,forwarding,gatewayDirectory);
await winlinkRadio.init;
const manualForwarding=new ManualForwarding(config,dir,forwarding);
await manualForwarding.init;
const forwardingScheduler=new ForwardingScheduler(config,dir,manualForwarding);await forwardingScheduler.init;
const syncOperations=new SyncOperations(forwarding);
async function syncNow(peer=config.forwardPeer){if(!config.features.bbs)throw new Error('BBS non configurata');return forwarding.start(peer);}
const messageMetadata=new ProgressiveMetadata(async item=>{const fields={...await messageTimes(item.id)};if(item.type==='P'&&(item.to==='RMS'||item.needsMetadata)){const f=await messageFields(item.id);Object.assign(fields,{from:f.From||item.from,to:f.To||item.to,subject:f.Title||item.subject,via:f.VIA||item.via});}return fields;});
const timestampCache=new Map();
async function messageTimes(id){if(timestampCache.has(id))return timestampCache.get(id);const pending=(async()=>{const f=await messageFields(id);let reference=new Date();try{reference=(await stat(path.join(root,'BPQMailChat','Mail','m_'+String(id).padStart(6,'0')+'.mes'))).mtime;}catch{}const receivedAt=bpqTimestamp(f.RX,reference);return {receivedAt,createdAt:bpqTimestamp(f.Sent,receivedAt?new Date(receivedAt):reference)};})().catch(error=>{timestampCache.delete(id);throw error;});timestampCache.set(id,pending);return pending;}
const metadataCache=new Map();let metadataKey=null,metadataKeyAt=0;
function messageFields(id){return metadataReads.run(id,()=>readMessageFields(id));}
async function readMessageFields(id,retry=true){let cached=metadataCache.get(id);if(cached&&Date.now()-cached.at<60000)return cached.fields;if(!metadataKey||Date.now()-metadataKeyAt>600000){const status=await bpq('/Mail/Status');metadataKey=status.match(/href=\/Mail\/Msgs\?([^\s>]+)/)?.[1];metadataKeyAt=Date.now();}if(!metadataKey)throw new Error('Metadati BBS non disponibili');const html=await bpq('/Mail/MsgDetails?'+metadataKey,{method:'POST',body:String(id)});const fields={};for(const input of html.matchAll(/<input\b[^>]*>/gi)){const name=input[0].match(/\bname=(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i),value=input[0].match(/\bvalue=(?:"([^"]*)"|'([^']*)'|([^\s>]*))/i);if(name)fields[name[1]??name[2]??name[3]]=decode(value?.[1]??value?.[2]??value?.[3]??'');}if(!('From' in fields)||!('Title' in fields)){metadataKey=null;metadataKeyAt=0;if(retry)return readMessageFields(id,false);throw Error('Metadati BBS non ancora disponibili');}metadataCache.set(id,{at:Date.now(),fields});return fields;}
async function messageAttachmentSummary(id){let file;try{file=await open(path.join(root,'BPQMailChat','Mail','m_'+String(id).padStart(6,'0')+'.mes'),'r');const header=Buffer.alloc(65540);const {bytesRead}=await file.read(header,0,header.length,0);return attachmentSummary(header.subarray(0,bytesRead));}catch{return {attachmentCount:0,attachmentBytes:0};}finally{await file?.close();}}
async function mailMetadata(list){const out=[];for(const item of list.filter(m=>m.type==='P')){const f=await messageFields(item.id);const m={...item,from:f.From||item.from,to:f.To||item.to,subject:f.Title||item.subject};const via=f.VIA||m.via,emailFrom=f.EFROM||'';if(m.to==='RMS'||m.from==='RMS'||/WINLINK|@/i.test(via+emailFrom)){const full={...m,via,emailFrom,address:m.to==='RMS'?via:m.to,fromAddress:emailFrom?(emailFrom.startsWith('@')?m.from+emailFrom:emailFrom):m.from};out.push({...full,...await messageAttachmentSummary(m.id),direction:mailDirection(full,config.sysop.call),folder:mailFolder(full,config.sysop.call)});}}return out;}
async function winlink(){const list=await mailMetadata(await messages(false));for(const m of list)Object.assign(m,await messageTimes(m.id));const today=new Date().toLocaleDateString('sv-SE',{timeZone:'UTC'}).replaceAll('-','').slice(2);let sync=cmsStatus('');try{sync=cmsStatus(await readFile(path.join(root,'Logs',`log_${today}_BBS.txt`),'utf8'));}catch{}const radioSession=winlinkRadio.snapshot();const history=forwardingHistory(await forwarding.logs().catch(()=>''),config.cmsPeer||'RMS');const last=history[0];const radioLatest=radioSession&&(radioSession.restoring||last&&Math.abs(Date.parse(last.startedAt)-Date.parse(radioSession.startedAt))<5000);return {messages:list,sync,account:config.sysop.call.replace(/-\d+$/,'')+'@winlink.org',requestedAt:lastCmsRequest||null,radioSession,transport:radioLatest?'radio':'internet',radioSupported:Boolean(config.radio&&(modemFamily(config.radio.driver)||packetPort(config))&&config.winlinkRadio?.catControl),modem:config.radio?.driver||null};}
function deleteMessage(id){return enqueueMailWrite(async()=>{const result=await deleteNativeMessage(id,bpq,{sysop:true});metadataCache.delete(id);timestampCache.delete(id);messageMetadata.invalidate(id);metadataReads.invalidate(id);mailReads.clear();mailKey=null;return result;});}
async function attachedMessage(id){const visible=await messages(false);const item=visible.find(m=>m.id===id);if(!item)throw new Error('Messaggio non disponibile');const file=path.join(root,'BPQMailChat','Mail','m_'+String(id).padStart(6,'0')+'.mes');const info=await stat(file);if(info.size>32*1024*1024)throw new Error('Messaggio troppo grande per il download web (32 MB)');const bytes=await readFile(file);const files=parseAttachments(bytes);const rebuilt=await sevenPlus.forMessage(id,visible);if(rebuilt?.file)files.push({...rebuilt.file,index:files.length});const encoded=item.subject.match(/^7\+\s+(.+?)\s+(\d+)\/(\d+)$/i);return {item,bytes,files,encoded:rebuilt?.metadata||(encoded?{name:safeName(encoded[1]),part:Number(encoded[2]),total:Number(encoded[3]),state:'unavailable'}:null)};}
let messageWriteQueue=Promise.resolve();
function enqueueMailWrite(work){const write=messageWriteQueue.then(work);messageWriteQueue=write.catch(()=>{});return write;}
function sendMessage(data){return enqueueMailWrite(()=>writeMessage(data));}
async function writeMessage(data){
const to=String(data.to||'').trim().toUpperCase(),subject=String(data.subject||'').trim(),text=String(data.text||'').trim(),type=String(data.type||'P');
if(!/^[A-Z0-9][A-Z0-9@.\/#_-]{1,79}$/.test(to)||!subject||subject.length>80||/[\x00-\x1f\x7f]/.test(subject)||!text||text.includes('\0')||Buffer.byteLength(text)>32000||!['P','B'].includes(type))throw new Error('Controlla destinatario, oggetto (max 80 caratteri) e testo (max 32 KB)');
const files=data.files||[];if(files.length&&(type!=='P'||!/^RMS[/:]/i.test(to)))throw Error('Gli allegati in uscita sono disponibili per le email Winlink');
if(Buffer.byteLength(text.replace(/\r?\n/g,'\r\n'))+files.reduce((n,f)=>n+f.size,0)>uploadLimits.messageBytes)throw Error('Testo e allegati superano 80 KB complessivi');
const previous=new Set((await messages()).map(m=>m.id));
// A separate native compose session prevents a reader from replacing its attachments.
const composePage=await bpq('/Webmail'),key=composePage.match(/WMB\?([^>\s]+)/)?.[1];if(!key)throw Error('WebMail BPQ non disponibile');await bpq('/WebMail/NewMsg?'+key);
const form=outgoingForm({to,subject,text,type,files});
const response=await bpq('/WebMail/EMSave?'+key,{method:'POST',body:form});
if(/alert\(/i.test(response)&&!/(sent|saved|created)/i.test(response))throw new Error(plain(response.match(/alert\(["']([^"']+)/)?.[1]||'BPQ ha rifiutato il messaggio'));
// A successful write must be visible in BPQ's message list, not inferred from HTTP 200.
mailReads.clear();const list=await messages();const expectedTo=/^RMS[/:]/.test(to)||/@[^@]*\./.test(to)?'RMS':to.split('@')[0];const created=list.find(m=>!previous.has(m.id)&&ownCall(m.from,config.sysop.call)&&m.subject===subject&&(m.to===expectedTo||m.to===to.split('@')[0]));
if(!created)throw new Error('BPQ non ha confermato il salvataggio. Controlla la lista prima di riprovare.');
if(files.length){const saved=await readFile(path.join(root,'BPQMailChat','Mail','m_'+String(created.id).padStart(6,'0')+'.mes'));verifySavedAttachments(saved,files);}
return {id:created.id,attachmentCount:files.length};
}
setInterval(()=>{for(const [token,s] of sessions)if(s.expires<Date.now()){s.terminal?.close();sessions.delete(token);}},30000).unref();
const server=http.createServer(async(req,res)=>{
try{
const host=req.headers.host||'';
if(!/^(localhost|127\.0\.0\.1|192\.168\.\d{1,3}\.\d{1,3}|10\.\d{1,3}\.\d{1,3}\.\d{1,3}|172\.(1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3})$/.test(host.split(':')[0])||host.split(':')[1]!==String(port)){json(res,403,{error:'Host non autorizzato'});return;}
res.setHeader('X-Content-Type-Options','nosniff');res.setHeader('X-Frame-Options','DENY');res.setHeader('Referrer-Policy','same-origin');res.setHeader('Content-Security-Policy',"default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data: blob: https://tile.openstreetmap.org; connect-src 'self'; worker-src 'self'; frame-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'");
const url=new URL(req.url,'http://'+host);
if(url.pathname==='/ui-config.js'&&req.method==='GET'){res.writeHead(200,{'Content-Type':'text/javascript; charset=utf-8','Cache-Control':'no-cache'});res.end('globalThis.BPQ_DEFAULT_LANGUAGE='+JSON.stringify(config.language||null)+';');return;}
if(url.pathname==='/health'&&req.method==='GET'){json(res,200,{service:'bpq-console',pid:process.pid});return;}
if(req.method==='POST'&&req.headers.origin!=='http://'+host){json(res,403,{error:'Origine non autorizzata'});return;}
if(url.pathname==='/api/login'&&req.method==='POST'){
const ip=req.socket.remoteAddress;let a=attempts.get(ip);if(a&&a.until>Date.now()&&a.count>=10){json(res,429,{error:'Troppi tentativi. Riprova tra 15 minuti.'});return;}if(!a||a.until<Date.now())a={count:0,until:Date.now()+15*60000};
const data=await body(req);const user=await authenticate(String(data.user||''),String(data.password||''));if(!user){a.count++;attempts.set(ip,a);json(res,401,{error:'Credenziali BPQ non valide per il pannello sysop'});return;}
attempts.delete(ip);const token=randomBytes(32).toString('hex'),csrf=randomBytes(24).toString('hex');sessions.set(token,{...user,csrf,expires:Date.now()+8*3600000});res.setHeader('Set-Cookie',`alnode=${token}; HttpOnly; SameSite=Strict; Path=/; Max-Age=28800`);json(res,200,{...user,csrf});return;
}
if(url.pathname.startsWith('/api/')){
const user=session(req);if(!user){json(res,401,{error:'Accedi con le credenziali BPQ'});return;}
const capability=url.pathname.startsWith('/api/terminal')?'terminal':url.pathname.startsWith('/api/chat')?'chat':url.pathname.startsWith('/api/monitor')?'monitor':url.pathname.startsWith('/api/winlink')?'winlink':url.pathname.startsWith('/api/forwarding')||url.pathname.startsWith('/api/messages')||url.pathname==='/api/sync'?'bbs':null;if(capability&&!config.features[capability]){json(res,409,{error:'Servizio non configurato in BPQ'});return;}
if(req.method==='POST'&&!equal(req.headers['x-csrf-token']||'',user.csrf)){json(res,403,{error:'Sessione non valida. Ricarica la pagina.'});return;}
if(url.pathname.startsWith('/api/terminal')){
if(!config.telnetPort)throw new Error('Porta Telnet BPQ non configurata');
if(!user.terminal)user.terminal=new Terminal(async()=>{const c=await loadConfig();return c.sysop;},{port:config.telnetPort,...config.telnetPrompts});
const terminal=user.terminal;
if(url.pathname==='/api/terminal'&&req.method==='GET'){const after=Number(url.searchParams.get('after')||0);if(!Number.isSafeInteger(after)||after<0)throw new Error('Cursore non valido');json(res,200,terminal.snapshot(after));return;}
if(url.pathname==='/api/terminal/connect'&&req.method==='POST'){json(res,200,await terminal.connect());return;}
if(url.pathname==='/api/terminal/disconnect'&&req.method==='POST'){terminal.disconnect();json(res,200,terminal.snapshot());return;}
if(url.pathname==='/api/terminal/send'&&req.method==='POST'){terminal.send((await body(req)).text);json(res,200,{ok:true});return;}
}
if(url.pathname==='/api/session'){json(res,200,{call:user.call,name:user.name,csrf:user.csrf,config:publicConfig(config)});return;}
if(url.pathname==='/api/monitor'&&req.method==='GET'){const after=Number(url.searchParams.get('after')||0);if(!Number.isSafeInteger(after)||after<0)throw new Error('Cursore monitor non valido');json(res,200,monitor.snapshot(after));return;}
if(url.pathname==='/api/monitor/connect'&&req.method==='POST'){json(res,200,await monitor.connect());return;}
if(url.pathname==='/api/monitor/disconnect'&&req.method==='POST'){monitor.disconnect();json(res,200,{ok:true});return;}
if(url.pathname==='/api/chat'&&req.method==='GET'){json(res,200,chat.snapshot());return;}
if(url.pathname==='/api/chat/connect'&&req.method==='POST'){json(res,200,await chat.connect());return;}
if(url.pathname==='/api/chat/disconnect'&&req.method==='POST'){chat.disconnect();json(res,200,{ok:true});return;}
if(url.pathname==='/api/chat/send'&&req.method==='POST'){const data=await body(req);chat.send(data.text,data.to);json(res,200,{ok:true});return;}
if(url.pathname==='/api/chat/topic'&&req.method==='POST'){chat.changeTopic((await body(req)).topic);json(res,200,{ok:true});return;}
if(url.pathname==='/api/logout'&&req.method==='POST'){const token=req.headers.cookie.match(/alnode=([a-f0-9]+)/)?.[1];user.terminal?.close();sessions.delete(token);res.setHeader('Set-Cookie','alnode=; HttpOnly; SameSite=Strict; Path=/; Max-Age=0');json(res,200,{ok:true});return;}
if(url.pathname==='/api/journal'&&req.method==='GET'){json(res,200,await journal.snapshot());return;}
if(url.pathname==='/api/stations/location'&&req.method==='POST'){const data=await body(req);json(res,200,await journal.saveLocation(String(data.call||''),String(data.locator||'')));return;}
if(url.pathname==='/api/sync/jobs'&&req.method==='GET'){json(res,200,[...syncOperations.jobs.values()].filter(j=>!j.endedAt).map(j=>syncOperations.snapshot(j)));return;}
if(url.pathname==='/api/sync/jobs'&&req.method==='POST'){
const data=await body(req);let spec;
if(data.kind==='forwarding'&&config.features.bbs){const route=manualForwarding.routes.find(r=>r.id===data.peer),profile=(await forwarding.profiles()).find(p=>p.call===data.peer);if(!route&&!profile)throw Error('Percorso di forwarding non configurato');spec={kind:data.kind,peer:route?.peer||profile.call,label:route?.label||profile.call,frequency:route?.frequencyMHz||Number(profile?.frequency?.[0])||null,mode:route?.mode||profile?.frequency?.[1]||null,client:route?manualForwarding:null,run:signal=>route?manualForwarding.startRoute(route.id,{signal}):forwarding.start(profile.call,{signal})};}
else if(data.kind==='winlink-radio'&&config.features.winlink){const channel=await gatewayDirectory.selected(String(data.channelId||''));spec={kind:data.kind,peer:config.cmsPeer||'RMS',label:channel.call,frequency:channel.dialHz/1e6,mode:channel.radioMode||channel.mode,client:winlinkRadio,run:signal=>winlinkRadio.start(channel.id,{signal})};}
else if(data.kind==='winlink-internet'&&config.features.winlink){const peer=config.cmsPeer||'RMS';spec={kind:data.kind,peer,label:'Winlink CMS · Internet',run:signal=>forwarding.start(peer,{signal})};}
else throw Error('Tipo di sincronizzazione non disponibile');json(res,202,syncOperations.start(spec));return;}
const syncJob=url.pathname.match(/^\/api\/sync\/jobs\/([a-f0-9-]{36})(\/abort)?$/);if(syncJob&&req.method==='GET'&&!syncJob[2]){json(res,200,syncOperations.get(syncJob[1]));return;}if(syncJob&&req.method==='POST'&&syncJob[2]){json(res,200,await syncOperations.abort(syncJob[1]));return;}
if(url.pathname==='/api/forwarding'&&req.method==='GET'){const data=await forwarding.snapshot();json(res,200,{...data,manualSession:manualForwarding.snapshot(),schedules:forwardingScheduler.snapshot(),profiles:manualForwarding.displayProfiles(data.profiles).map(p=>{const s=forwardingScheduler.snapshot().find(s=>s.route===p.call&&s.enabled);return s?{...p,scheduled:true,manualOnly:false,enabled:true,interval:s.intervalSeconds,nextEstimated:s.nextAt}:p;})});return;}
if(url.pathname==='/api/forwarding/manual/restore'&&req.method==='POST'){json(res,200,await manualForwarding.restore());return;}
const fwdStart=url.pathname.match(/^\/api\/forwarding\/([A-Z0-9-]{1,32})\/sync$/);if(fwdStart&&req.method==='POST'){const peer=fwdStart[1];json(res,200,manualForwarding.routes.some(r=>r.id===peer)?await manualForwarding.startRoute(peer):await forwarding.start(peer));return;}
if(url.pathname==='/api/dashboard'){json(res,200,await dashboard());return;}
if(url.pathname==='/api/radio/control'&&req.method==='GET'){json(res,200,await radioControl.snapshot());return;}
if(url.pathname==='/api/aprs/settings'&&req.method==='GET'){json(res,200,await aprsSettings.snapshot());return;}
if(url.pathname==='/api/aprs/activity/start'&&req.method==='POST'){json(res,200,await aprsActivity.start());return;}
if(url.pathname==='/api/aprs/activity'&&req.method==='GET'){await aprsActivity.init;json(res,200,aprsActivity.snapshot());return;}
if(url.pathname==='/api/aprs/settings'&&req.method==='POST'){json(res,200,await aprsSettings.save(await body(req)));return;}
if(url.pathname==='/api/radio/ports'&&req.method==='GET'){json(res,200,radioPorts.state||await radioPorts.sample());return;}
const radioPortUpdate=url.pathname.match(/^\/api\/radio\/ports\/(\d+)$/);if(radioPortUpdate&&req.method==='POST'){json(res,200,await radioPorts.update(Number(radioPortUpdate[1]),await body(req)));return;}
if(url.pathname==='/api/radio/control'&&req.method==='POST'){json(res,200,await radioControl.update(await body(req)));return;}
if(url.pathname==='/api/telemetry'&&req.method==='GET'){json(res,200,telemetry);return;}
if(url.pathname==='/api/messages'&&req.method==='GET'){json(res,200,messageReadState.decorate(await messages()));return;}
const attachmentRoute=url.pathname.match(/^\/api\/messages\/(\d+)\/attachments(?:\/(\d+))?$/);
if(attachmentRoute&&req.method==='GET'){const id=Number(attachmentRoute[1]),message=await attachedMessage(id);if(attachmentRoute[2]===undefined){json(res,200,{files:message.files.map(({data,...f})=>f),encoded:message.encoded});return;}const file=message.files[Number(attachmentRoute[2])];if(!file)throw new Error('Allegato non disponibile');if(url.searchParams.get('text')==='1'){if(file.mime!=='text/plain')throw new Error('Questo file non ha anteprima testuale');const bytes=file.data.subarray(0,128*1024);let text;try{text=new TextDecoder('utf8',{fatal:true}).decode(bytes);}catch{text=bytes.toString('latin1');}json(res,200,{text,truncated:file.size>bytes.length});return;}const preview=url.searchParams.get('preview')==='1'&&(file.mime.startsWith('image/')||file.mime==='application/pdf');res.setHeader('Content-Security-Policy',"default-src 'none'; sandbox; frame-ancestors 'self'");res.setHeader('X-Frame-Options','SAMEORIGIN');res.writeHead(200,{'Content-Type':preview?file.mime:'application/octet-stream','Content-Length':file.size,'Content-Disposition':`${preview?'inline':'attachment'}; filename="${file.name.replace(/[^A-Za-z0-9._ -]/g,'_')}"; filename*=UTF-8''${encodeURIComponent(file.name)}`,'Cache-Control':'no-store'});res.end(file.data);return;}
const sourceRoute=url.pathname.match(/^\/api\/messages\/(\d+)\/source$/);if(sourceRoute&&req.method==='GET'){const m=await attachedMessage(Number(sourceRoute[1]));res.writeHead(200,{'Content-Type':'application/octet-stream','Content-Length':m.bytes.length,'Content-Disposition':`attachment; filename="messaggio-${m.item.id}.txt"`,'Cache-Control':'no-store'});res.end(m.bytes);return;}
if(url.pathname==='/api/winlink/gateways'&&req.method==='GET'){json(res,200,await gatewayDirectory.snapshot(url.searchParams.get('refresh')==='1'));return;}
if(url.pathname==='/api/winlink/radio/restore'&&req.method==='POST'){json(res,200,await winlinkRadio.restore());return;}
if(url.pathname==='/api/winlink/radio/sync'&&req.method==='POST'){const data=await body(req);json(res,200,await winlinkRadio.start(String(data.channelId||'')));return;}
if(url.pathname==='/api/winlink'&&req.method==='GET'){const data=await winlink();data.messages=messageReadState.decorate(data.messages);json(res,200,data);return;}
if(url.pathname==='/api/winlink/sync'&&req.method==='POST'){if(Date.now()-lastCmsRequest<10000)throw new Error('Sincronizzazione già richiesta. Attendi qualche secondo.');await syncNow(config.cmsPeer||'RMS');lastCmsRequest=Date.now();json(res,200,{ok:true});return;}
const readRoute=url.pathname.match(/^\/api\/messages\/(\d+)\/read$/);if(readRoute&&req.method==='POST'){const item=(await messages()).find(m=>m.id===Number(readRoute[1]));if(!item)throw new Error('Messaggio non disponibile');json(res,200,await messageReadState.mark(item));return;}
if(/^\/api\/messages\/\d+\/delete$/.test(url.pathname)&&req.method==='POST'){json(res,200,await deleteMessage(Number(url.pathname.split('/')[3])));return;}
if(/^\/api\/messages\/\d+$/.test(url.pathname)&&req.method==='GET'){const id=url.pathname.split('/').pop();const {key}=await mailContext();const msg=parseMessage(await bpq('/WebMail/WM?'+key+'&'+id));if(!msg)throw new Error('Messaggio non disponibile');try{const raw=await attachedMessage(Number(id));const text=b2Body(raw.bytes);if(text!==null)msg.text=text.replace(/\r\n|\r/g,'\n');}catch{}const fields=await messageFields(Number(id));json(res,200,{id:Number(id),...msg,to:fields.To||msg.to,via:fields.VIA||msg.via||'',...await messageTimes(Number(id))});return;}
if(url.pathname==='/api/messages'&&req.method==='POST'){json(res,201,await sendMessage(await readSubmission(req)));return;}
if(url.pathname==='/api/sync'&&req.method==='POST'){await syncNow();json(res,200,{ok:true});return;}
json(res,404,{error:'Operazione non disponibile'});return;
}
if(req.method!=='GET'){json(res,405,{error:'Metodo non disponibile'});return;}
const vendor=url.pathname.match(/^\/vendor\/pdfjs\/(pdf\.min\.mjs|pdf\.worker\.min\.mjs|(?:standard_fonts|cmaps)\/[A-Za-z0-9_.-]+)$/);if(vendor&&!vendor[1].includes('..')){const bytes=await readFile(path.join(dir,'public','vendor','pdfjs',vendor[1]));res.writeHead(200,{'Content-Type':vendor[1].endsWith('.mjs')?'text/javascript':'application/octet-stream','Cache-Control':'public, max-age=86400'});res.end(bytes);return;}
const files={'/detach.js':'detach.js','/detach.css':'detach.css','/terminal-window':'terminal-window.html','/terminal-window.js':'terminal-window.js','/aprs-symbols.js':'aprs-symbols.js','/vendor/aprs-symbols/primary.png':'vendor/aprs-symbols/primary.png','/vendor/aprs-symbols/alternate.png':'vendor/aprs-symbols/alternate.png','/vendor/aprs-symbols/README.md':'vendor/aprs-symbols/README.md','/vendor/aprs-symbols/COPYRIGHT.md':'vendor/aprs-symbols/COPYRIGHT.md','/busy.js':'busy.js','/busy.css':'busy.css','/vendor/leaflet/leaflet.js':'vendor/leaflet/leaflet.js','/vendor/leaflet/leaflet.css':'vendor/leaflet/leaflet.css','/aprs-activity.js':'aprs-activity.js','/aprs-activity.css':'aprs-activity.css','/aprs.js':'aprs.js','/aprs.css':'aprs.css','/radio-ports.js':'radio-ports.js','/radio-ports.css':'radio-ports.css','/compose-attachments.js':'compose-attachments.js','/compose-attachments.css':'compose-attachments.css','/i18n.js':'i18n.js','/i18n.css':'i18n.css','/sync-state.js':'sync-state.js','/sync-progress.js':'sync-progress.js','/sync-progress.css':'sync-progress.css','/radio-control.js':'radio-control.js','/radio-control.css':'radio-control.css','/terminal.js':'terminal.js','/terminal.css':'terminal.css','/winlink-radio.js':'winlink-radio.js','/winlink-radio.css':'winlink-radio.css','/forwarding.js':'forwarding.js','/forwarding.css':'forwarding.css','/journal.js':'journal.js','/journal.css':'journal.css','/world-land.json':'world-land.json','/monitor.js':'monitor.js','/monitor.css':'monitor.css','/':'index.html','/app.js':'app.js','/enhancements.js':'enhancements.js','/notifications.js':'notifications.js','/winlink.js':'winlink.js','/mission.js':'mission.js','/attachments.js':'attachments.js','/mission.css':'mission.css','/style.css':'style.css','/dark.css':'dark.css'};const file=files[url.pathname];if(!file){json(res,404,{error:'Pagina non trovata'});return;}const bytes=await readFile(path.join(dir,'public',file));res.writeHead(200,{'Content-Type':file.endsWith('.png')?'image/png':file.endsWith('.md')?'text/plain; charset=utf-8':file.endsWith('.json')?'application/json':file.endsWith('.css')?'text/css; charset=utf-8':file.endsWith('.js')?'text/javascript; charset=utf-8':'text/html; charset=utf-8','Cache-Control':'no-cache'});res.end(bytes);
}catch(e){json(res,502,{error:e.message||'BPQ temporaneamente non disponibile'});}
});
server.listen(port,'0.0.0.0',()=>console.log(`BPQ Console: http://127.0.0.1:${port}`));