Harden generic installation and startup, preserve station settings and coalesce mail reads
This commit is contained in:
1 parent
3f6d35690b
commit
5358cad695
14 files changed
+398
-146
No files matched your search
+13
-8
@@ -1,4 +1,5 @@
|
||||
import {Terminal} from './terminal.mjs';
|
||||
import {SingleFlight} from './single-flight.mjs';
|
||||
import http from 'node:http';
|
||||
import {Journal} from './journal.mjs';
|
||||
import {GatewayDirectory,modemFamily} from './winlink-gateways.mjs';
|
||||
@@ -38,6 +39,7 @@ function varaCpuSample(){execFile('powershell.exe',['-NoProfile','-NonInteractiv
|
||||
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
|
||||
@@ -47,15 +49,16 @@ async function bpqRequest(url, options={}) {
|
||||
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()});
|
||||
}
|
||||
async function mailContext(){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};}
|
||||
async function messages(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);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;}if(includeTimes)for(const m of list)Object.assign(m,await messageTimes(m.id));return list;}
|
||||
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);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;}if(includeTimes)for(const m of list)Object.assign(m,await messageTimes(m.id));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 found=users.find(u=>equal(u.user.toLowerCase(),user.toLowerCase())&&equal(u.password,password)&&u.user===config.sysop.user);return found?{call:found.call,name:found.user,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():Promise.resolve([])]);
|
||||
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');
|
||||
@@ -76,10 +79,11 @@ async function syncNow(peer=config.forwardPeer){if(!config.features.bbs)throw ne
|
||||
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(()=>{timestampCache.delete(id);return {receivedAt:null,createdAt:null};});timestampCache.set(id,pending);return pending;}
|
||||
const metadataCache=new Map();let metadataKey=null,metadataKeyAt=0;
|
||||
async function messageFields(id){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]??'');}metadataCache.set(id,{at:Date.now(),fields});return fields;}
|
||||
function messageFields(id){return metadataReads.run(id,()=>readMessageFields(id));}
|
||||
async function readMessageFields(id){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]??'');}metadataCache.set(id,{at:Date.now(),fields});return fields;}
|
||||
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,direction:mailDirection(full,config.sysop.call),folder:mailFolder(full,config.sysop.call)});}}return out;}
|
||||
async function winlink(){const list=await mailMetadata(await messages());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)&&config.winlinkRadio?.catControl),modem:config.radio?.driver||null};}
|
||||
async function deleteMessage(id){const list=await messages();if(!list.some(m=>m.id===id))throw new Error('Messaggio non presente');const {key}=await mailContext();await bpq('/WebMail/WMDel/'+id+'?'+key);metadataCache.delete(id);if((await messages()).some(m=>m.id===id))throw new Error('BPQ non ha confermato la cancellazione');return {ok:true};}
|
||||
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)&&config.winlinkRadio?.catControl),modem:config.radio?.driver||null};}
|
||||
async function deleteMessage(id){const list=await messages();if(!list.some(m=>m.id===id))throw new Error('Messaggio non presente');const {key}=await mailContext();await bpq('/WebMail/WMDel/'+id+'?'+key);metadataCache.delete(id);timestampCache.delete(id);metadataReads.invalidate(id);mailReads.clear();if((await messages()).some(m=>m.id===id))throw new Error('BPQ non ha confermato la cancellazione');return {ok:true};}
|
||||
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)};}
|
||||
async function sendMessage(data){
|
||||
const to=String(data.to||'').trim().toUpperCase(),subject=String(data.subject||'').trim(),text=String(data.text||'').trim(),type=String(data.type||'P');
|
||||
@@ -90,7 +94,7 @@ async function sendMessage(data){
|
||||
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.
|
||||
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]));
|
||||
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.');
|
||||
return {id:created.id};
|
||||
}
|
||||
@@ -101,6 +105,7 @@ const server=http.createServer(async(req,res)=>{
|
||||
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:; 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==='/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};
|
||||
@@ -109,7 +114,7 @@ const server=http.createServer(async(req,res)=>{
|
||||
}
|
||||
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/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;}
|
||||
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');
|
||||
|
||||
Reference in new issue
Block a user