Add amber phosphor Telnet terminal with isolated BPQ sessions
This commit is contained in:
1 parent
b5ee05f257
commit
3f6d35690b
8 files changed
+96
-5
No files matched your search
@@ -122,3 +122,15 @@ Il profilo cmsPeer (RMS per impostazione predefinita) deve avere script Internet
|
||||
Lo stato di recupero è nel file locale winlink-radio.session.json, escluso da Git. Dopo un riavvio il pannello riprende il ripristino; una modifica manuale concorrente del profilo sospende il ripristino automatico e richiede verifica tramite il pulsante dedicato. Lasciare il pannello in esecuzione durante lo scambio. Lo stato iniziale conferma la richiesta a BPQ; l’esito e i conteggi provengono dai log, senza presumere la consegna della posta.
|
||||
|
||||
Verifica: `node --test test.mjs forwarding.test.mjs winlink-radio.test.mjs`.
|
||||
|
||||
## Terminale Telnet
|
||||
|
||||
La sezione **Terminale** apre una sessione Telnet reale verso BPQ sullo stesso PC, usando TCPPORT rilevata in BPQ32.cfg. **Collega** esegue l’accesso automatico con l’utente sysop configurato; le credenziali di accesso non vengono incluse nel testo restituito al browser. Non richiede VARA o un modem specifico. Se manca TCPPORT, il pulsante di navigazione viene nascosto.
|
||||
|
||||
Il terminale usa fosfori giallo ambra, scanline leggere, bagliore e cursore lampeggiante (fermo quando il sistema richiede movimento ridotto). Invio invia il comando; ↑ e ↓ richiamano la cronologia della pagina. Il testo è selezionabile e copiabile. Pulisci svuota solo la schermata; Salva testo scarica quanto visualizzato; Disconnetti chiude il socket. Lo scorrimento automatico si sospende risalendo nel testo e riprende con Torna al fondo.
|
||||
|
||||
Ogni sessione web ha un proprio collegamento e buffer in memoria, senza condivisione del terminale fra accessi. Le API richiedono autenticazione e CSRF per i comandi. Il server si collega soltanto al Telnet BPQ locale: non accetta host o porte forniti dal browser. Logout e scadenza dell’accesso chiudono la sessione; il socket viene chiuso anche dopo 90 secondi senza consultazione del terminale oppure 15 minuti senza comandi. Nessun registro viene salvato automaticamente su disco.
|
||||
|
||||
È una console a righe per il nodo BPQ e le sue applicazioni: non emula applicazioni a schermo intero VT100. Il testo remoto viene visualizzato come testo, senza eseguire HTML o sequenze di controllo ANSI. Limiti: 1000 caratteri per comando, 200.000 caratteri di output in memoria e 100 comandi nella cronologia del browser.
|
||||
|
||||
Verifica: `node --test test.mjs forwarding.test.mjs winlink-radio.test.mjs terminal.test.mjs`.
|
||||
+1
-1
@@ -22,7 +22,7 @@ export async function loadConfig(){
|
||||
if(!detected.users.length)throw new Error('Nessun utente Telnet sysop in BPQ32.cfg');
|
||||
const radio=detected.radioPorts.find(p=>p.id===saved.radioPort)||detected.radioPorts[0]||null;
|
||||
const httpPort=saved.httpPort||detected.httpPort;if(!httpPort)throw new Error('HTTPPORT BPQ non rilevata: eseguire Install.ps1');
|
||||
const features={bbs:detected.apps.some(a=>a.command==='BBS'),chat:detected.apps.some(a=>a.command==='CHAT')&&!!detected.telnetPort,monitor:!!detected.monitorPort,winlink:detected.winlink&&detected.apps.some(a=>a.command==='BBS'),vara:!!radio&&/^VARA/i.test(radio.driver),radio:!!radio};
|
||||
const features={terminal:!!detected.telnetPort,bbs:detected.apps.some(a=>a.command==='BBS'),chat:detected.apps.some(a=>a.command==='CHAT')&&!!detected.telnetPort,monitor:!!detected.monitorPort,winlink:detected.winlink&&detected.apps.some(a=>a.command==='BBS'),vara:!!radio&&/^VARA/i.test(radio.driver),radio:!!radio};
|
||||
return {...detected,...saved,root,httpPort,radio,features,port:Number(process.env.BPQ_CONSOLE_PORT||saved.port||8090),sysop:detected.users.find(u=>u.user===saved.sysopUser)||detected.users[0]};
|
||||
}
|
||||
export function publicConfig(c){return {call:c.sysop.call,nodeCall:c.nodeCall,alias:c.alias,locator:c.locator,apps:c.apps,radio:c.radio,ports:c.ports,features:c.features,forwardPeer:c.forwardPeer||'',cmsPeer:c.cmsPeer||'RMS'};}
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
<!doctype html>
|
||||
<html lang="it"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="theme-color" content="#101916"><title>BPQ — Radio & BBS</title><link rel="stylesheet" href="/style.css"><link rel="stylesheet" href="/dark.css"><link rel="stylesheet" href="/mission.css"><script defer src="/app.js"></script><script type="module" src="/enhancements.js"></script><script defer src="/winlink.js"></script><script defer src="/mission.js"></script><script defer src="/attachments.js"></script><link rel="stylesheet" href="/monitor.css"><script defer src="/monitor.js"></script><link rel="stylesheet" href="/journal.css"><script defer src="/journal.js"></script><link rel="stylesheet" href="/forwarding.css"><script defer src="/forwarding.js"></script><link rel="stylesheet" href="/winlink-radio.css"><script defer src="/winlink-radio.js"></script></head>
|
||||
<html lang="it"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="theme-color" content="#101916"><title>BPQ — Radio & BBS</title><link rel="stylesheet" href="/style.css"><link rel="stylesheet" href="/dark.css"><link rel="stylesheet" href="/mission.css"><script defer src="/app.js"></script><script type="module" src="/enhancements.js"></script><script defer src="/winlink.js"></script><script defer src="/mission.js"></script><script defer src="/attachments.js"></script><link rel="stylesheet" href="/monitor.css"><script defer src="/monitor.js"></script><link rel="stylesheet" href="/journal.css"><script defer src="/journal.js"></script><link rel="stylesheet" href="/forwarding.css"><script defer src="/forwarding.js"></script><link rel="stylesheet" href="/winlink-radio.css"><script defer src="/winlink-radio.js"></script><link rel="stylesheet" href="/terminal.css"><script defer src="/terminal.js"></script></head>
|
||||
<body>
|
||||
<section id="login" class="login-screen"><div class="login-art"><span class="eyebrow">BPQ NETWORK</span><h1>BPQ<br><em>Radio Console</em></h1><div class="signal-art"><i></i><i></i><i></i><i></i><b>STAZIONE</b></div><p>La tua stazione, in un unico pannello.</p></div><form id="login-form" class="login-card"><span class="brand">◉ BPQ<span>CONSOLE</span></span><h2>Benvenuto in stazione.</h2><p>Accedi con l’utente e la password Telnet del tuo BPQ.</p><label>Utente<input name="user" autocomplete="username" required placeholder="Il tuo utente BPQ"></label><label>Password<input name="password" type="password" autocomplete="current-password" required></label><button class="primary" type="submit">Entra nel pannello <span>→</span></button><div id="login-error" class="error" role="alert"></div><small>Created by IU2EUG · PC e rete locale</small></form></section>
|
||||
<div id="shell" hidden><aside class="sidebar"><a class="brand" href="#home">◉ BPQ<span>RADIO CONSOLE</span></a><div class="side-label">LA TUA STAZIONE</div><nav><button data-page="home" class="active"><span>▦</span> Panoramica</button><button data-page="bbs"><span>▤</span> BBS <b id="nav-count">—</b></button><button data-page="network"><span>⌘</span> Rete & nodi</button></nav><div class="side-station">Stazione BPQ</div><div class="profile"><div class="avatar">BP</div><div>Sysop<small>BPQ</small></div><button id="logout" title="Esci" aria-label="Esci dal pannello">↗</button></div></aside>
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
#terminal{height:calc(100dvh - 76px);display:flex;flex-direction:column;min-height:560px;padding:24px 28px}.terminal-heading{display:flex;align-items:center;justify-content:space-between;gap:18px;margin-bottom:20px;flex-shrink:0}.terminal-heading h1{font-size:28px;font-weight:500}.terminal-heading p{font-size:11px;color:var(--muted);margin-top:5px}.terminal-actions{display:flex;gap:9px}.terminal-actions button{font-size:11px}.phosphor-case{flex:1;min-height:0;display:flex;flex-direction:column;border-radius:16px;border:1px solid #51452b;background:#11110e;padding:7px;box-shadow:0 16px 45px #0005,inset 0 1px #8e774822;overflow:hidden}.phosphor-top,.phosphor-bottom{display:flex;justify-content:space-between;align-items:center;gap:18px;color:#9e844d;font:10px Consolas,'Courier New',monospace;letter-spacing:1px;flex-shrink:0;padding:14px 19px}.phosphor-top{border-bottom:1px solid #4a3a1c}.phosphor-top>span:first-child{display:flex;align-items:center;gap:10px}.phosphor-top i{display:inline-block;width:6px;height:6px;background:#5d5033;border-radius:50%}.phosphor-top i.online{background:#ffd477;box-shadow:0 0 9px #ffbd4d}.phosphor-screen{flex:1;min-height:0;overflow:auto;padding:24px 26px;color:#ffd376;background:radial-gradient(ellipse at center,#241d0d 0%,#131106 70%,#0b0b06 100%);box-shadow:inset 0 0 55px #000a;scrollbar-color:#72572a #151207;position:relative;isolation:isolate}.phosphor-screen:before{content:'';position:absolute;inset:0;min-height:100%;pointer-events:none;background:repeating-linear-gradient(0deg,transparent 0 2px,#0002 2px 3px);z-index:1}.phosphor-screen pre{font:14px/1.55 Consolas,'Courier New',monospace;white-space:pre-wrap;overflow-wrap:anywhere;tab-size:8;letter-spacing:.2px;text-shadow:0 0 5px #ffc14b66;margin:0;position:relative;z-index:2;user-select:text}.phosphor-screen pre::selection{background:#94702f;color:#fff2c4}.phosphor-cursor{display:inline-block;color:#ffda84;font:16px Consolas,monospace;animation:phosphor-blink 1.1s steps(1) infinite;text-shadow:0 0 8px #ffc354}#terminal-form{display:flex;align-items:center;gap:12px;margin:0;padding:12px 20px;border-top:1px solid #4a3a1c;background:#1c180e;color:#ffd376;flex-shrink:0}#terminal-form label{font:18px Consolas,monospace}#terminal-input{flex:1;width:0;min-width:0;background:transparent;border:0;border-radius:0;box-shadow:none;color:#ffda8a;font:14px Consolas,'Courier New',monospace;padding:10px 0;caret-color:#ffe2a2}#terminal-input::placeholder{color:#82704b}#terminal-input:focus-visible{outline:0;box-shadow:0 1px #c09c4a}#terminal-send{background:#30250f;border:1px solid #665126;color:#e9c779;font:11px Consolas,monospace;padding:10px 13px;border-radius:5px}.phosphor-bottom{font-size:9px;padding:12px 18px;letter-spacing:.5px;flex-wrap:wrap}.phosphor-bottom button{background:transparent;border:0;color:#ffda84;font:inherit;padding:0}@keyframes phosphor-blink{50%{opacity:0}}@media(prefers-reduced-motion:reduce){.phosphor-cursor{animation:none}}@media(max-width:850px){.terminal-heading{align-items:flex-start;flex-direction:column}.terminal-actions{flex-wrap:wrap}.phosphor-screen{padding:16px}.phosphor-screen pre{font-size:12px}.phosphor-top{font-size:9px;letter-spacing:.3px}}@media(max-width:600px){#terminal{padding:20px 14px;height:calc(100dvh - 175px);min-height:510px}.terminal-heading h1{font-size:25px}.terminal-actions button{padding:8px 10px}.phosphor-top{padding:12px 10px}#terminal-form{padding:10px 12px}.phosphor-bottom>span:nth-child(2){display:none}nav{flex-wrap:wrap}}
|
||||
|
||||
@media(min-width:601px){.sidebar:has([data-page=terminal]) nav{min-height:100px;overflow-y:auto;flex-shrink:1;scrollbar-width:thin}.sidebar:has([data-page=terminal])>.brand,.sidebar:has([data-page=terminal])>.side-label,.sidebar:has([data-page=terminal])>.profile{flex-shrink:0}.sidebar:has([data-page=terminal])>.side-station{padding-block:14px;flex-shrink:0}}
|
||||
@@ -0,0 +1,22 @@
|
||||
(() => {
|
||||
const nav=document.createElement('button');nav.dataset.page='terminal';nav.innerHTML='<span>▸_</span> Terminale';nav.onclick=()=>navigate('terminal');$('nav').append(nav);
|
||||
const section=document.createElement('section');section.id='terminal';section.className='page';section.hidden=true;section.innerHTML=`<div class="terminal-heading"><div><h1>Terminale</h1><p>BPQ · Telnet</p></div><div class="terminal-actions"><button id="terminal-clear" class="secondary">Pulisci</button><button id="terminal-export" class="secondary">Salva testo</button><button id="terminal-connect" class="primary">Collega</button><button id="terminal-stop" class="secondary" hidden>Disconnetti</button></div></div><div class="phosphor-case"><div class="phosphor-top"><span><i id="terminal-led"></i> BPQ / REMOTE TERMINAL</span><span id="terminal-state" role="status">OFFLINE</span></div><div class="phosphor-screen" id="terminal-screen" tabindex="0" aria-label="Terminale Telnet BPQ"><pre id="terminal-output" aria-live="off"></pre><span class="phosphor-cursor" aria-hidden="true">▌</span></div><form id="terminal-form" autocomplete="off"><label for="terminal-input">></label><input id="terminal-input" aria-label="Comando Telnet" placeholder="Collega il terminale per iniziare" spellcheck="false" autocapitalize="off" maxlength="1000" disabled><button type="submit" id="terminal-send" disabled aria-label="Invia comando">INVIO ↵</button></form><div class="phosphor-bottom"><span id="terminal-endpoint">TELNET · BPQ LOCALE</span><span>↑ ↓ cronologia · Invio per inviare</span><button type="button" id="terminal-follow" hidden>↓ Torna al fondo</button></div></div>`;$('main').append(section);
|
||||
let cursor=0,busy=false,state='offline',buffer='',following=true,history=[],historyIndex=0,draft='',sending=false,generation=0;
|
||||
const area=$('#terminal-screen'),output=$('#terminal-output'),input=$('#terminal-input');
|
||||
const previousNavigate=navigate;navigate=function(next){previousNavigate(next);if(next==='terminal'){$('#breadcrumb').textContent='Stazione / Terminale';poll();}};
|
||||
function bottom(){area.scrollTop=area.scrollHeight;following=true;$('#terminal-follow').hidden=true;}
|
||||
function append(text){buffer=(buffer+text).slice(-200000);output.textContent=buffer;if(following)bottom();}
|
||||
function status(data){const wasOnline=state==='online';state=data.state;const online=state==='online',connecting=state==='connecting';$('#terminal-state').textContent=data.error||({online:'ONLINE',connecting:'COLLEGAMENTO…',offline:'OFFLINE',error:'ERRORE'}[state]||state);$('#terminal-led').classList.toggle('online',online);$('#terminal-connect').hidden=online||connecting;$('#terminal-stop').hidden=!online&&!connecting;input.disabled=!online;$('#terminal-send').disabled=!online||sending;input.placeholder=online?'Scrivi un comando…':'Collega il terminale per iniziare';$('#terminal-endpoint').textContent='TELNET · 127.0.0.1:'+data.port;if(online&&!wasOnline&&page==='terminal')input.focus();}
|
||||
async function poll(){if(!csrf||busy||!station.features.terminal)return;busy=true;const current=generation;try{const d=await api('/terminal?after='+cursor);if(current!==generation)return;if(d.latest<cursor){cursor=0;buffer='';}status(d);for(const e of d.events)append(e.text);cursor=d.latest;}catch(e){if(page==='terminal')$('#terminal-state').textContent=e.message;}finally{busy=false;}}
|
||||
$('#terminal-connect').onclick=async()=>{const button=$('#terminal-connect');button.disabled=true;try{const d=await api('/terminal/connect',{method:'POST',body:'{}'});buffer='';output.textContent='';following=true;cursor=0;status(d);await poll();}catch(e){toast(e.message);}finally{button.disabled=false;}};
|
||||
$('#terminal-stop').onclick=async()=>{try{status(await api('/terminal/disconnect',{method:'POST',body:'{}'}));await poll();}catch(e){toast(e.message);}};
|
||||
$('#terminal-form').onsubmit=async e=>{e.preventDefault();if(sending||state!=='online')return;const text=input.value;sending=true;$('#terminal-send').disabled=true;try{await api('/terminal/send',{method:'POST',body:JSON.stringify({text})});if(text&&history.at(-1)!==text)history.push(text);history=history.slice(-100);historyIndex=history.length;draft='';input.value='';await poll();}catch(e){toast(e.message);}finally{sending=false;$('#terminal-send').disabled=state!=='online';if(state==='online')input.focus();}};
|
||||
input.addEventListener('keydown',e=>{if(e.key==='ArrowUp'){e.preventDefault();if(historyIndex===history.length)draft=input.value;if(historyIndex>0)input.value=history[--historyIndex];}else if(e.key==='ArrowDown'){e.preventDefault();if(historyIndex<history.length)historyIndex++;input.value=historyIndex===history.length?draft:history[historyIndex];}});
|
||||
area.addEventListener('scroll',()=>{following=area.scrollHeight-area.scrollTop-area.clientHeight<40;$('#terminal-follow').hidden=following;});$('#terminal-follow').onclick=bottom;
|
||||
$('#terminal-clear').onclick=()=>{buffer='';output.textContent='';bottom();input.focus();};
|
||||
$('#terminal-export').onclick=()=>{if(!buffer){toast('Il terminale è vuoto');return;}const url=URL.createObjectURL(new Blob([buffer],{type:'text/plain;charset=utf-8'})),a=document.createElement('a');a.href=url;a.download='BPQ-terminal-'+new Date().toISOString().replace(/[:.]/g,'-')+'.txt';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);};
|
||||
document.addEventListener('station-ready',()=>{generation++;cursor=0;buffer='';output.textContent='';history=[];historyIndex=0;nav.hidden=!station.features.terminal;if(page==='terminal')poll();});
|
||||
const logout=$('#logout').onclick;$('#logout').onclick=async()=>{generation++;buffer='';output.textContent='';history=[];input.value='';await logout();};
|
||||
setInterval(()=>{if(csrf&&page==='terminal')poll();},700);
|
||||
window.addEventListener('hashchange',()=>{if(location.hash==='#terminal'&&page!=='terminal')navigate('terminal');});if(location.hash==='#terminal')navigate('terminal');
|
||||
})();
|
||||
+14
-3
@@ -1,3 +1,4 @@
|
||||
import {Terminal} from './terminal.mjs';
|
||||
import http from 'node:http';
|
||||
import {Journal} from './journal.mjs';
|
||||
import {GatewayDirectory,modemFamily} from './winlink-gateways.mjs';
|
||||
@@ -52,7 +53,7 @@ function equal(a,b){const aa=Buffer.from(a),bb=Buffer.from(b);return aa.length==
|
||||
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)sessions.delete(token);return null;}
|
||||
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 val=i=>jobs[i].status==='fulfilled'?jobs[i].value:null;
|
||||
@@ -93,6 +94,7 @@ async function sendMessage(data){
|
||||
if(!created)throw new Error('BPQ non ha confermato il salvataggio. Controlla la lista prima di riprovare.');
|
||||
return {id:created.id};
|
||||
}
|
||||
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||'';
|
||||
@@ -109,6 +111,15 @@ const server=http.createServer(async(req,res)=>{
|
||||
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;}
|
||||
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});
|
||||
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;}
|
||||
@@ -118,7 +129,7 @@ const server=http.createServer(async(req,res)=>{
|
||||
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];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/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/forwarding'&&req.method==='GET'){json(res,200,await forwarding.snapshot());return;}
|
||||
@@ -142,7 +153,7 @@ const server=http.createServer(async(req,res)=>{
|
||||
}
|
||||
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={'/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('.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);
|
||||
const files={'/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('.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}`));
|
||||
@@ -0,0 +1,35 @@
|
||||
import net from 'node:net';
|
||||
import {StringDecoder} from 'node:string_decoder';
|
||||
|
||||
// Telnet commands may be split across TCP packets, including subnegotiations.
|
||||
export class TelnetText {
|
||||
constructor(reply){this.reply=reply;this.state='text';this.command=0;}
|
||||
read(chunk){const out=[];for(const b of chunk){switch(this.state){
|
||||
case 'text':if(b===255)this.state='iac';else out.push(b);break;
|
||||
case 'iac':if(b===255){out.push(b);this.state='text';}else if(b===250)this.state='sub';else if([251,252,253,254].includes(b)){this.command=b;this.state='option';}else this.state='text';break;
|
||||
case 'option':if(this.command===251)this.reply(Buffer.from([255,254,b]));if(this.command===253)this.reply(Buffer.from([255,252,b]));this.state='text';break;
|
||||
case 'sub':if(b===255)this.state='sub-iac';break;
|
||||
case 'sub-iac':this.state=b===240?'text':'sub';break;
|
||||
}}return Buffer.from(out);}
|
||||
}
|
||||
export class Terminal {
|
||||
constructor(credentials,options={}){this.credentials=credentials;this.options=options;this.state='offline';this.events=[];this.seq=0;this.lastAccess=Date.now();this.lastInput=Date.now();this.timer=setInterval(()=>{if(this.socket&&!this.socket.destroyed&&(Date.now()-this.lastAccess>90000||Date.now()-this.lastInput>15*60000))this.disconnect('Sessione chiusa per inattività');},10000);this.timer.unref();}
|
||||
event(text){if(!text)return;this.events.push({id:++this.seq,text});let size=this.events.reduce((n,e)=>n+e.text.length,0);while(this.events.length>500||size>200000)size-=this.events.shift().text.length;}
|
||||
snapshot(after=0){this.lastAccess=Date.now();return {state:this.state,events:this.events.filter(e=>e.id>after),latest:this.seq,port:this.options.port,error:this.error||null};}
|
||||
async connect(){if(this.state==='connecting'||this.socket&&!this.socket.destroyed)return this.snapshot();this.state='connecting';let credentials;try{credentials=await this.credentials();}catch{this.state='error';throw new Error('Credenziali Telnet BPQ non disponibili');}if(this.state!=='connecting')return this.snapshot();this.error=null;this.events=[];this.stage=0;this.auth='';this.escape='';this.pendingCR=false;this.decoder=new StringDecoder('utf8');this.lastAccess=this.lastInput=Date.now();const socket=net.createConnection({host:'127.0.0.1',port:this.options.port});this.socket=socket;const telnet=new TelnetText(b=>socket.write(b));socket.setTimeout(15000);
|
||||
socket.on('timeout',()=>{if(this.state==='connecting')socket.destroy(new Error('Accesso Telnet non confermato'));});
|
||||
socket.on('error',()=>{if(this.socket!==socket)return;this.state='error';this.error='Connessione Telnet BPQ non disponibile';this.event('\n[Connessione Telnet non disponibile]\n');});
|
||||
socket.on('close',()=>{if(this.socket!==socket)return;if(this.pendingCR){this.event('\n');this.pendingCR=false;}if(this.state!=='error')this.state='offline';this.event('\n[Sessione terminata]\n');});
|
||||
socket.on('data',chunk=>{if(this.socket!==socket)return;const text=this.decoder.write(telnet.read(chunk));if(this.stage<3){this.auth=(this.auth+text).slice(-12000);
|
||||
if(this.stage===0&&/Username:/i.test(this.auth)){socket.write(credentials.user+'\r');this.stage=1;this.auth='';return;}
|
||||
if(this.stage===1&&/Password:/i.test(this.auth)){socket.write(credentials.password+'\r');this.stage=2;this.auth='';return;}
|
||||
if(this.stage===2){if(/invalid|incorrect|denied|Username:/i.test(this.auth)){socket.destroy(new Error('Accesso rifiutato'));return;}const welcome=this.auth.search(/Welcome|[A-Z0-9]{1,6}:[A-Z0-9-]+>/i);if(welcome>=0){this.stage=3;this.state='online';socket.setTimeout(0);this.output(this.auth.slice(welcome));this.auth='';}}return;
|
||||
}this.output(text);});return this.snapshot();}
|
||||
output(text){let out='';for(const c of text){if(this.pendingCR){out+='\n';this.pendingCR=false;if(c==='\n'||c==='\0')continue;}
|
||||
if(this.escape){this.escape+=c;if(this.escape.length>128||/^\x1b\[[0-?]*[ -/]*[@-~]$/.test(this.escape)||this.escape.length===2&&c!=='[')this.escape='';continue;}
|
||||
if(c==='\x1b'){this.escape=c;continue;}if(c==='\r'){this.pendingCR=true;continue;}if(c==='\b'){out=out.slice(0,-1);continue;}if(c==='\n'||c==='\t'||c.charCodeAt(0)>=32)out+=c;
|
||||
}this.event(out);}
|
||||
send(text){if(this.state!=='online'||!this.socket||this.socket.destroyed)throw new Error('Collega prima il terminale');if(typeof text!=='string'||text.length>1000||/[\x00-\x1f\x7f]/.test(text))throw new Error('Invia un solo comando, massimo 1000 caratteri');this.lastInput=this.lastAccess=Date.now();this.event(text+'\n');this.socket.write(text+'\r');}
|
||||
disconnect(reason='Disconnessione richiesta'){this.lastInput=Date.now();if(this.socket&&!this.socket.destroyed)this.socket.destroy();this.state='offline';this.event('\n['+reason+']\n');}
|
||||
close(){this.disconnect();clearInterval(this.timer);}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import {test} from 'node:test';import assert from 'node:assert/strict';import net from 'node:net';import {once} from 'node:events';import {Terminal,TelnetText} from './terminal.mjs';
|
||||
test('Telnet handles fragmented negotiation, escaped IAC and subnegotiations',()=>{const replies=[],t=new TelnetText(b=>replies.push([...b]));assert.deepEqual([...t.read(Buffer.from([65,255,251]))],[65]);assert.deepEqual([...t.read(Buffer.from([1,66,255,250,24,4,255]))],[66]);assert.deepEqual([...t.read(Buffer.from([240,67,255,255]))],[67,255]);t.read(Buffer.from([255,253,3]));assert.deepEqual(replies,[[255,254,1],[255,252,3]]);});
|
||||
test('terminal authenticates privately, preserves fragmented output, sends lines and disconnects',async()=>{
|
||||
const sockets=new Set(),received=[];const server=net.createServer(socket=>{sockets.add(socket);socket.on('close',()=>sockets.delete(socket));socket.write('User');setImmediate(()=>socket.write('name:'));let stage=0,buffer='';socket.on('data',chunk=>{buffer+=chunk;let pos;while((pos=buffer.indexOf('\r'))>=0){const line=buffer.slice(0,pos);buffer=buffer.slice(pos+1);received.push(line);if(stage++===0)socket.write('Password:');else if(stage===2){socket.write('secret-example\r\nWelcome to TEST\r');setImmediate(()=>socket.write('\nTEST:N0TEST>'));}else socket.write('Response: '+line+'\r\n');}});});server.listen(0,'127.0.0.1');await once(server,'listening');const t=new Terminal(async()=>({user:'fixture',password:'secret-example'}),{port:server.address().port});
|
||||
const until=async fn=>{for(let i=0;i<100&&!fn();i++)await new Promise(r=>setTimeout(r,10));assert.ok(fn());};
|
||||
try{await Promise.all([t.connect(),t.connect()]);await until(()=>t.state==='online');await until(()=>t.events.some(e=>e.text.includes('TEST:N0TEST>')));const text=t.snapshot().events.map(e=>e.text).join('');assert.equal(text,'Welcome to TEST\nTEST:N0TEST>');assert.ok(!text.includes('secret-example'));assert.ok(!text.includes('fixture'));assert.equal(received.filter(x=>x==='fixture').length,1);t.send('INFO');await until(()=>received.includes('INFO'));assert.throws(()=>t.send('INFO\rC EVIL'),/un solo comando/);assert.throws(()=>t.send('x'.repeat(1001)),/1000/);await until(()=>t.events.some(e=>e.text.includes('Response: INFO')));const last=t.seq;assert.equal(t.snapshot(last).events.length,0);t.output('\x1b[31mred\x1b[0m\r\0next');assert.equal(t.events.at(-1).text,'red\nnext');t.disconnect();assert.throws(()=>t.send('INFO'),/Collega/);assert.equal(t.state,'offline');}finally{t.close();for(const socket of sockets)socket.destroy();server.close();await once(server,'close');}
|
||||
});
|
||||
test('terminal transcript stays bounded and reconnect history does not grow indefinitely',()=>{const t=new Terminal(async()=>({}),{port:1});try{for(let i=0;i<800;i++)t.event('x'.repeat(500));assert.ok(t.events.length<=500);assert.ok(t.events.reduce((n,e)=>n+e.text.length,0)<=200000);}finally{t.close();}});
|
||||
Reference in new issue
Block a user