Support custom BPQ Telnet prompts and banners, fix installer arguments
This commit is contained in:
1 parent
33d2cc4fbd
commit
2b00b1cbbd
14 files changed
+168
-44
No files matched your search
+3
-3
@@ -1,4 +1,4 @@
|
|||||||
param([string]$BpqRoot,[int]$Port,[int]$HttpPort,[int]$RadioPort,[string]$SysopUser,[string]$ForwardPeer,[string]$CmsPeer,[string]$VaraLogPath,[string]$NodeExe,[switch]$EnableRadioCAT,[switch]$DisableRadioCAT,[switch]$CheckOnly,[switch]$AutoStart,[switch]$EnableLAN,[switch]$Restart)
|
param([string]$BpqRoot,[int]$Port,[int]$HttpPort,[int]$RadioPort,[string]$SysopUser,[string]$ForwardPeer,[string]$CmsPeer,[string]$VaraLogPath,[string]$NodeExe,[ValidateSet("it","en")][string]$Language,[switch]$EnableRadioCAT,[switch]$DisableRadioCAT,[switch]$CheckOnly,[switch]$AutoStart,[switch]$EnableLAN,[switch]$Restart)
|
||||||
$ErrorActionPreference='Stop'
|
$ErrorActionPreference='Stop'
|
||||||
if($EnableRadioCAT -and $DisableRadioCAT){throw 'Scegliere una sola opzione CAT.'}
|
if($EnableRadioCAT -and $DisableRadioCAT){throw 'Scegliere una sola opzione CAT.'}
|
||||||
if($AutoStart -and !$CheckOnly -and ($env:BPQ_CONSOLE_CONFIG -or $env:BPQ_ROOT -or $env:BPQ_CONSOLE_PORT)){throw 'Per -AutoStart usare console.config.json nella cartella del progetto, senza override BPQ_* temporanei.'}
|
if($AutoStart -and !$CheckOnly -and ($env:BPQ_CONSOLE_CONFIG -or $env:BPQ_ROOT -or $env:BPQ_CONSOLE_PORT)){throw 'Per -AutoStart usare console.config.json nella cartella del progetto, senza override BPQ_* temporanei.'}
|
||||||
@@ -30,8 +30,8 @@ if($targetPort -ge 1024 -and $targetPort -le 65535){
|
|||||||
if($listener){$owner=Get-CimInstance Win32_Process -Filter "ProcessId=$($listener[0].OwningProcess)";if($owner.Name -ne 'node.exe' -or !$owner.CommandLine -or $owner.CommandLine.IndexOf((Join-Path $PSScriptRoot 'server.mjs'),[StringComparison]::OrdinalIgnoreCase) -lt 0){throw "Porta $targetPort occupata da un altro processo. Specificare -Port con una porta libera."}}
|
if($listener){$owner=Get-CimInstance Win32_Process -Filter "ProcessId=$($listener[0].OwningProcess)";if($owner.Name -ne 'node.exe' -or !$owner.CommandLine -or $owner.CommandLine.IndexOf((Join-Path $PSScriptRoot 'server.mjs'),[StringComparison]::OrdinalIgnoreCase) -lt 0){throw "Porta $targetPort occupata da un altro processo. Specificare -Port con una porta libera."}}
|
||||||
}
|
}
|
||||||
$nodeArgs=@((Join-Path $PSScriptRoot 'install.mjs'),'--bpq-root',$BpqRoot,'--config-path',$configPath)
|
$nodeArgs=@((Join-Path $PSScriptRoot 'install.mjs'),'--bpq-root',$BpqRoot,'--config-path',$configPath)
|
||||||
$mapping=@{Port='port';HttpPort='http-port';RadioPort='radio-port';SysopUser='sysop-user';ForwardPeer='forward-peer';CmsPeer='cms-peer';VaraLogPath='vara-log'}
|
$mapping=@{Port='port';HttpPort='http-port';RadioPort='radio-port';SysopUser='sysop-user';ForwardPeer='forward-peer';CmsPeer='cms-peer';VaraLogPath='vara-log';Language='language'}
|
||||||
foreach($name in $mapping.Keys){if($PSBoundParameters.ContainsKey($name)){$nodeArgs+=@('--'+$mapping[$name],[string](Get-Variable -Name $name -ValueOnly))}}
|
foreach($name in $mapping.Keys){if($PSBoundParameters.ContainsKey($name)){$nodeArgs+=@(('--'+$mapping[$name]),[string](Get-Variable -Name $name -ValueOnly))}}
|
||||||
if(!$VaraLogPath){$vara=Get-Process -Name VARA -ErrorAction SilentlyContinue | Select-Object -First 1;if($vara.Path){$varaLog=Join-Path (Split-Path $vara.Path) 'VARAHF.log';if(Test-Path -LiteralPath $varaLog){$nodeArgs+=@('--vara-log',$varaLog)}}}
|
if(!$VaraLogPath){$vara=Get-Process -Name VARA -ErrorAction SilentlyContinue | Select-Object -First 1;if($vara.Path){$varaLog=Join-Path (Split-Path $vara.Path) 'VARAHF.log';if(Test-Path -LiteralPath $varaLog){$nodeArgs+=@('--vara-log',$varaLog)}}}
|
||||||
if($EnableRadioCAT){$nodeArgs+='--enable-radio-cat'}
|
if($EnableRadioCAT){$nodeArgs+='--enable-radio-cat'}
|
||||||
if($DisableRadioCAT){$nodeArgs+='--disable-radio-cat'}
|
if($DisableRadioCAT){$nodeArgs+='--disable-radio-cat'}
|
||||||
|
|||||||
@@ -4,10 +4,14 @@ A local web dashboard for BPQ32: node status, BBS, Winlink, forwarding, chat, tr
|
|||||||
|
|
||||||
## Interface language
|
## Interface language
|
||||||
|
|
||||||
Use the Italian / UK flag switch in the login screen or dashboard header to select **Italiano** or **English**. On the first visit, the initial language is chosen from the first preferred browser language: Italian for `it` / `it-*`, English otherwise. After that the saved choice is used; there is no Auto mode. Switching language applies immediately, without signing out or interrupting a radio session. Dates and numbers follow the selected language; the local timezone is unchanged. Mail, bulletin subjects and bodies, chat messages, attachment contents, terminal output and radio traffic remain original. No online translation service is used.
|
Use the Italian / UK flag switch in the login screen or dashboard header to select **Italiano** or **English**. Set `"language": "en"` or `"language": "it"` in `console.config.json` to choose the default for new browsers (or install with `-Language en` / `node install.mjs --language en`). If omitted, the first preferred browser language selects Italian for `it` / `it-*`, English otherwise. A language already saved in a browser takes precedence. After that the saved choice is used; there is no Auto mode. Switching language applies immediately, without signing out or interrupting a radio session. Dates and numbers follow the selected language; the local timezone is unchanged. Mail, bulletin subjects and bodies, chat messages, attachment contents, terminal output and radio traffic remain original. No online translation service is used.
|
||||||
|
|
||||||
Interface copy is maintained in `public/i18n.js`; add new UI phrases and parameterised status patterns there. Mark custom data widgets with `data-no-i18n` so their content is preserved.
|
Interface copy is maintained in `public/i18n.js`; add new UI phrases and parameterised status patterns there. Mark custom data widgets with `data-no-i18n` so their content is preserved.
|
||||||
|
|
||||||
|
## Telnet login compatibility
|
||||||
|
|
||||||
|
Terminal and Chat read `LOGINPROMPT` and `PASSWORDPROMPT` from the Telnet port in `BPQ32.cfg`. Standard `Username:`, `Login:`, `User:` and `Password:` prompts also work. `PASSWORD` is not the prompt setting. Custom CTEXT banners do not need the word Welcome or a node prompt; both `ALIAS:CALL>` and `ALIAS:CALL}` work. After the password, the clients wait for 400 ms of quiet after non-empty banner text; a repeated login/password prompt or explicit denial rejects the login. Password echoes are removed before displaying the terminal banner, and Chat discards the Telnet banner before sending `CHAT`. A server that sends no text at all after the password times out instead of reporting an unconfirmed login as successful. Restart BPQ Console after changing prompt settings.
|
||||||
|
|
||||||
## Requirements
|
## Requirements
|
||||||
|
|
||||||
- Windows and Windows PowerShell 5.1 or later.
|
- Windows and Windows PowerShell 5.1 or later.
|
||||||
|
|||||||
@@ -1,18 +1,26 @@
|
|||||||
import net from 'node:net';
|
import net from 'node:net';
|
||||||
import {StringDecoder} from 'node:string_decoder';
|
import {StringDecoder} from 'node:string_decoder';
|
||||||
|
import {TelnetText,TelnetLogin} from './telnet-login.mjs';
|
||||||
|
|
||||||
export function parseUser(line){const m=line.match(/^([A-Z0-9]+(?:-\d+)?)\s+at\s+(\S+)\s+(.+?),\s*(.*?)\s+\[([^\]]+)\] Idle for (\d+) seconds/i);return m?{call:m[1],node:m[2],name:m[3],qth:m[4],topic:m[5],idle:Number(m[6])}:null;}
|
export function parseUser(line){const m=line.match(/^([A-Z0-9]+(?:-\d+)?)\s+at\s+(\S+)\s+(.+?),\s*(.*?)\s+\[([^\]]+)\] Idle for (\d+) seconds/i);return m?{call:m[1],node:m[2],name:m[3],qth:m[4],topic:m[5],idle:Number(m[6])}:null;}
|
||||||
export class Chat {
|
export class Chat {
|
||||||
constructor(credentials,options={}){this.options=options;this.call=options.call||'';this.credentials=credentials;this.state='offline';this.events=[];this.seq=0;this.users=[];this.topics=['General'];this.links=[];this.topic='General';this.lastAccess=Date.now();this.timer=setInterval(()=>{if(this.state==='online'&&Date.now()-this.lastAccess>120000)this.disconnect();else if(this.state==='online'&&Date.now()-this.lastRoster>30000)this.roster()},10000);this.timer.unref();}
|
constructor(credentials,options={}){this.options=options;this.call=options.call||'';this.credentials=credentials;this.state='offline';this.events=[];this.seq=0;this.users=[];this.topics=['General'];this.links=[];this.topic='General';this.lastAccess=Date.now();this.timer=setInterval(()=>{if(this.state==='online'&&Date.now()-this.lastAccess>120000)this.disconnect();else if(this.state==='online'&&Date.now()-this.lastRoster>30000)this.roster()},10000);this.timer.unref();}
|
||||||
event(type,text,sender=null,to=null){this.events.push({id:++this.seq,type,text,sender,to,at:new Date().toISOString()});if(this.events.length>300)this.events.shift();}
|
event(type,text,sender=null,to=null){this.events.push({id:++this.seq,type,text,sender,to,at:new Date().toISOString()});if(this.events.length>300)this.events.shift();}
|
||||||
snapshot(){this.lastAccess=Date.now();return {state:this.state,events:this.events,users:this.users,topics:this.topics,links:this.links,topic:this.topic,call:this.call};}
|
snapshot(){this.lastAccess=Date.now();return {state:this.state,events:this.events,users:this.users,topics:this.topics,links:this.links,topic:this.topic,call:this.call};}
|
||||||
async connect(){if(this.socket&&!this.socket.destroyed)return this.snapshot();const {user,password}=await this.credentials();this.users=[];this.links=[];this.events=[];this.state='connecting';this.section='';this.stage=0;this.buffer='';this.authBuffer='';this.decoder=new StringDecoder('utf8');this.iac=0;this.socket=net.createConnection({host:'127.0.0.1',port:this.options.port||8100});this.socket.setTimeout(15000);this.socket.on('timeout',()=>{if(this.state!=='online')this.socket.destroy(new Error('Timeout di accesso chat'));});this.socket.on('error',e=>{this.state='error';this.event('system','Chat non disponibile: '+e.message)});this.socket.on('close',()=>{if(this.state!=='error')this.state='offline';this.event('system','Disconnesso dalla chat')});
|
async connect(){
|
||||||
this.socket.on('data',chunk=>{const bytes=[];for(const b of chunk){if(this.iac===1){if(b===255){bytes.push(b);this.iac=0}else if([251,252,253,254].includes(b))this.iac=2;else this.iac=0;continue}if(this.iac===2){this.iac=0;continue}if(b===255){this.iac=1;continue}bytes.push(b)}const text=this.decoder.write(Buffer.from(bytes)).replace(/\x1b\[[0-9;]*m/g,'');this.authBuffer=(this.authBuffer+text).slice(-5000);
|
if(this.state==='connecting'||this.socket&&!this.socket.destroyed)return this.snapshot();this.state='connecting';
|
||||||
if(this.stage===0&&/Username:/i.test(this.authBuffer)){this.write(user);this.stage=1;this.authBuffer='';return;}
|
let credentials;try{credentials=await this.credentials();}catch{this.state='error';throw new Error('Credenziali Telnet BPQ non disponibili');}
|
||||||
if(this.stage===1&&/Password:/i.test(this.authBuffer)){this.write(password);this.stage=2;this.authBuffer='';return;}
|
if(this.state!=='connecting')return this.snapshot();this.users=[];this.links=[];this.events=[];this.section='';this.stage=0;this.buffer='';this.decoder=new StringDecoder('utf8');
|
||||||
if(this.stage===2&&/Welcome|[A-Z0-9]{1,6}:[A-Z0-9-]+>/i.test(this.authBuffer)){this.write('CHAT');this.stage=3;this.authBuffer='';return;}
|
const socket=net.createConnection({host:'127.0.0.1',port:this.options.port||8100});this.socket=socket;const telnet=new TelnetText(b=>socket.write(b));socket.setTimeout(15000);
|
||||||
if(this.stage<3)return;this.buffer+=text.replace(/\r\n/g,'\n').replace(/\r/g,'\n');const lines=this.buffer.split('\n');this.buffer=lines.pop();for(const line of lines)this.line(line.trim());});
|
this.login=new TelnetLogin(socket,credentials,this.options,()=>{if(this.socket!==socket)return;this.stage=3;this.buffer='';this.write('CHAT');});
|
||||||
|
socket.on('timeout',()=>{if(this.state!=='online')socket.destroy(new Error('Timeout di accesso chat'));});
|
||||||
|
socket.on('error',e=>{if(this.socket!==socket)return;this.state='error';this.event('system','Chat non disponibile: '+e.message)});
|
||||||
|
socket.on('close',()=>{if(this.socket!==socket)return;this.login?.close();if(this.state!=='error')this.state='offline';this.event('system','Disconnesso dalla chat')});
|
||||||
|
socket.on('data',chunk=>{if(this.socket!==socket)return;const text=this.decoder.write(telnet.read(chunk)).replace(/\x1b\[[0-9;]*m/g,'');
|
||||||
|
if(this.stage<3){this.login.read(text);return;}
|
||||||
|
this.buffer+=text.replace(/\r\n/g,'\n').replace(/\r/g,'\n');const lines=this.buffer.split('\n');this.buffer=lines.pop();for(const line of lines)this.line(line.trim());});
|
||||||
this.lastAccess=Date.now();return this.snapshot();}
|
this.lastAccess=Date.now();return this.snapshot();}
|
||||||
|
|
||||||
line(line){if(!line)return;if(line.includes('[BPQChatServer-')){this.state='online';this.socket.setTimeout(0);this.event('system','Connesso alla chat come '+this.call);setTimeout(()=>{if(this.state==='online')this.roster()},1000);return;}
|
line(line){if(!line)return;if(line.includes('[BPQChatServer-')){this.state='online';this.socket.setTimeout(0);this.event('system','Connesso alla chat come '+this.call);setTimeout(()=>{if(this.state==='online')this.roster()},1000);return;}
|
||||||
if(/Already connected/i.test(line)){this.event('system','BPQ ha rilevato una precedente sessione. Se la connessione si chiude, premi Connetti.');return;}
|
if(/Already connected/i.test(line)){this.event('system','BPQ ha rilevato una precedente sessione. Se la connessione si chiude, premi Connetti.');return;}
|
||||||
if(/Disconnected from Stream/i.test(line)){this.socket?.end();return;}
|
if(/Disconnected from Stream/i.test(line)){this.socket?.end();return;}
|
||||||
@@ -30,5 +38,5 @@ export class Chat {
|
|||||||
roster(){this.lastRoster=Date.now();this.write('/U');setTimeout(()=>{if(this.state==='online')this.write('/T')},500);setTimeout(()=>{if(this.state==='online')this.write('/P')},1000);}
|
roster(){this.lastRoster=Date.now();this.write('/U');setTimeout(()=>{if(this.state==='online')this.write('/T')},500);setTimeout(()=>{if(this.state==='online')this.write('/P')},1000);}
|
||||||
send(text,to=''){if(this.state!=='online')throw new Error('Connettiti alla chat prima di scrivere');if(typeof text!=='string'||!text.trim()||text.length>500||/[\r\n\x00-\x1f]/.test(text)||text.trim().startsWith('/'))throw new Error('Scrivi un messaggio su una sola riga, massimo 500 caratteri');if(to&&!/^[A-Z0-9]*\d[A-Z0-9]*(?:-\d+)?$/i.test(to))throw new Error('Nominativo non valido');this.write(to?'/S '+to.toUpperCase()+' '+text:text);this.event('message',text,this.call,to?to.toUpperCase():null);this.lastAccess=Date.now();}
|
send(text,to=''){if(this.state!=='online')throw new Error('Connettiti alla chat prima di scrivere');if(typeof text!=='string'||!text.trim()||text.length>500||/[\r\n\x00-\x1f]/.test(text)||text.trim().startsWith('/'))throw new Error('Scrivi un messaggio su una sola riga, massimo 500 caratteri');if(to&&!/^[A-Z0-9]*\d[A-Z0-9]*(?:-\d+)?$/i.test(to))throw new Error('Nominativo non valido');this.write(to?'/S '+to.toUpperCase()+' '+text:text);this.event('message',text,this.call,to?to.toUpperCase():null);this.lastAccess=Date.now();}
|
||||||
changeTopic(name){if(this.state!=='online')throw new Error('Chat non connessa');if(!/^[A-Za-z0-9_-]{1,24}$/.test(name))throw new Error('Nome stanza non valido');this.write('/T '+name);this.topic=name;this.event('system','Stanza selezionata: '+name);setTimeout(()=>this.state==='online'&&this.roster(),800);}
|
changeTopic(name){if(this.state!=='online')throw new Error('Chat non connessa');if(!/^[A-Za-z0-9_-]{1,24}$/.test(name))throw new Error('Nome stanza non valido');this.write('/T '+name);this.topic=name;this.event('system','Stanza selezionata: '+name);setTimeout(()=>this.state==='online'&&this.roster(),800);}
|
||||||
disconnect(){if(this.socket&&!this.socket.destroyed){this.write('/QUIT');this.socket.end();}this.state='offline';}
|
disconnect(){this.login?.close();if(this.socket&&!this.socket.destroyed){this.write('/QUIT');this.socket.end();}this.state='offline';}
|
||||||
}
|
}
|
||||||
+3
-2
@@ -10,18 +10,19 @@ export function parseConfig(text){
|
|||||||
const users=lines.flatMap(l=>{const m=l.match(/^USER\s*=\s*([^,]+),([^,]+),([^,]+),(.*)$/i);return m&&/\bsysop\b/i.test(m[4])?[{user:m[1].trim(),password:m[2],call:m[3].trim().toUpperCase()}]:[]});
|
const users=lines.flatMap(l=>{const m=l.match(/^USER\s*=\s*([^,]+),([^,]+),([^,]+),(.*)$/i);return m&&/\bsysop\b/i.test(m[4])?[{user:m[1].trim(),password:m[2],call:m[3].trim().toUpperCase()}]:[]});
|
||||||
const apps=lines.flatMap(l=>{const m=l.match(/^APPLICATION\s+\d+\s*,(.*)$/i);if(!m)return [];const fields=m[1].split(',').map(s=>s.trim());return fields[0]?[{command:fields[0].split('/')[0].toUpperCase(),call:(fields[2]||'').toUpperCase(),alias:fields[3]||''}]:[]});
|
const apps=lines.flatMap(l=>{const m=l.match(/^APPLICATION\s+\d+\s*,(.*)$/i);if(!m)return [];const fields=m[1].split(',').map(s=>s.trim());return fields[0]?[{command:fields[0].split('/')[0].toUpperCase(),call:(fields[2]||'').toUpperCase(),alias:fields[3]||''}]:[]});
|
||||||
let ports=[],current=null;
|
let ports=[],current=null;
|
||||||
for(const l of lines){if(/^PORT$/i.test(l)){current={id:ports.length+1,name:'',driver:'',settings:{}};continue;}if(/^ENDPORT$/i.test(l)){if(current){if(!current.driver)current.driver=current.protocol||current.type||'';ports.push(current)};current=null;continue;}if(current){const m=l.match(/^(PORTNUM|ID|DRIVER|TYPE|PROTOCOL)\s*=\s*(.*)$/i);if(m)current[({PORTNUM:'id',ID:'name',DRIVER:'driver',TYPE:'type',PROTOCOL:'protocol'})[m[1].toUpperCase()]]=m[1].toUpperCase()==='PORTNUM'?Number(m[2].trim()):m[2].trim();const s=l.match(/^(HTTPPORT|TCPPORT|FBBPORT|CMS)\s*=\s*(.*)$/i);if(s)current.settings[s[1].toUpperCase()]=s[2].trim();}}
|
for(const l of lines){if(/^PORT$/i.test(l)){current={id:ports.length+1,name:'',driver:'',settings:{}};continue;}if(/^ENDPORT$/i.test(l)){if(current){if(!current.driver)current.driver=current.protocol||current.type||'';ports.push(current)};current=null;continue;}if(current){const m=l.match(/^(PORTNUM|ID|DRIVER|TYPE|PROTOCOL)\s*=\s*(.*)$/i);if(m)current[({PORTNUM:'id',ID:'name',DRIVER:'driver',TYPE:'type',PROTOCOL:'protocol'})[m[1].toUpperCase()]]=m[1].toUpperCase()==='PORTNUM'?Number(m[2].trim()):m[2].trim();const s=l.match(/^(HTTPPORT|TCPPORT|FBBPORT|CMS|LOGINPROMPT|PASSWORDPROMPT)\s*=\s*(.*)$/i);if(s)current.settings[s[1].toUpperCase()]=s[2].trim();}}
|
||||||
const telnet=ports.find(p=>/^TELNET(?:\.DLL)?$/i.test(p.driver)),settings=telnet?.settings||{};
|
const telnet=ports.find(p=>/^TELNET(?:\.DLL)?$/i.test(p.driver)),settings=telnet?.settings||{};
|
||||||
for(const p of ports)delete p.settings;
|
for(const p of ports)delete p.settings;
|
||||||
const radioPorts=ports.filter(p=>!/TELNET|AXIP|LOOPBACK/i.test(p.driver)&&p.driver);
|
const radioPorts=ports.filter(p=>!/TELNET|AXIP|LOOPBACK/i.test(p.driver)&&p.driver);
|
||||||
const nodeCall=value('NODECALL'),sysop=users[0];
|
const nodeCall=value('NODECALL'),sysop=users[0];
|
||||||
return {nodeCall,call:sysop?.call||nodeCall.replace(/-\d+$/,''),alias:value('NODEALIAS'),locator:value('LOCATOR'),apps,ports,radioPorts,users,httpPort:Number(settings.HTTPPORT)||null,telnetPort:Number(settings.TCPPORT)||null,monitorPort:Number(settings.FBBPORT)||null,winlink:settings.CMS==='1'};
|
return {nodeCall,call:sysop?.call||nodeCall.replace(/-\d+$/,''),alias:value('NODEALIAS'),locator:value('LOCATOR'),apps,ports,radioPorts,users,httpPort:Number(settings.HTTPPORT)||null,telnetPort:Number(settings.TCPPORT)||null,monitorPort:Number(settings.FBBPORT)||null,telnetPrompts:{loginPrompt:settings.LOGINPROMPT||'',passwordPrompt:settings.PASSWORDPROMPT||''},winlink:settings.CMS==='1'};
|
||||||
}
|
}
|
||||||
export async function loadConfig(){
|
export async function loadConfig(){
|
||||||
const dir=path.dirname(fileURLToPath(import.meta.url));let saved={};
|
const dir=path.dirname(fileURLToPath(import.meta.url));let saved={};
|
||||||
try{saved=JSON.parse(await readFile(process.env.BPQ_CONSOLE_CONFIG||path.join(dir,'console.config.json'),'utf8'));}catch(e){if(e.code!=='ENOENT')throw e;}
|
try{saved=JSON.parse(await readFile(process.env.BPQ_CONSOLE_CONFIG||path.join(dir,'console.config.json'),'utf8'));}catch(e){if(e.code!=='ENOENT')throw e;}
|
||||||
if(!saved||typeof saved!=='object'||Array.isArray(saved))throw new Error('La configurazione locale deve essere un oggetto JSON');
|
if(!saved||typeof saved!=='object'||Array.isArray(saved))throw new Error('La configurazione locale deve essere un oggetto JSON');
|
||||||
const root=process.env.BPQ_ROOT||saved.bpqRoot||path.join(process.env.APPDATA||path.join(os.homedir(),'AppData','Roaming'),'BPQ32');
|
const root=process.env.BPQ_ROOT||saved.bpqRoot||path.join(process.env.APPDATA||path.join(os.homedir(),'AppData','Roaming'),'BPQ32');
|
||||||
|
if(saved.language!=null&&!['it','en'].includes(saved.language))throw new Error('language deve essere it oppure en');
|
||||||
const detected=parseConfig(await readFile(path.join(root,'BPQ32.cfg'),'utf8'));
|
const detected=parseConfig(await readFile(path.join(root,'BPQ32.cfg'),'utf8'));
|
||||||
if(!detected.users.length)throw new Error('Nessun utente Telnet sysop in BPQ32.cfg');
|
if(!detected.users.length)throw new Error('Nessun utente Telnet sysop in BPQ32.cfg');
|
||||||
if(saved.radioPort!=null&&!detected.radioPorts.some(p=>p.id===Number(saved.radioPort)))throw new Error('Porta radio configurata non rilevata: rieseguire Install.ps1');
|
if(saved.radioPort!=null&&!detected.radioPorts.some(p=>p.id===Number(saved.radioPort)))throw new Error('Porta radio configurata non rilevata: rieseguire Install.ps1');
|
||||||
|
|||||||
+4
-2
@@ -3,9 +3,9 @@ import assert from 'node:assert/strict';
|
|||||||
import vm from 'node:vm';
|
import vm from 'node:vm';
|
||||||
import {readFileSync} from 'node:fs';
|
import {readFileSync} from 'node:fs';
|
||||||
const source=readFileSync(new URL('./public/i18n.js',import.meta.url),'utf8');
|
const source=readFileSync(new URL('./public/i18n.js',import.meta.url),'utf8');
|
||||||
function client(languages=['it-IT'],saved=null){
|
function client(languages=['it-IT'],saved=null,defaultLanguage=null){
|
||||||
const storage=new Map(saved?[['bpq-language',saved]]:[]),events=[];
|
const storage=new Map(saved?[['bpq-language',saved]]:[]),events=[];
|
||||||
const context=vm.createContext({navigator:{languages},localStorage:{getItem:k=>storage.get(k),setItem:(k,v)=>storage.set(k,v)},document:{documentElement:{lang:''},readyState:'loading',body:null,addEventListener(){},querySelectorAll:()=>[],dispatchEvent:e=>events.push(e)},addEventListener(){},CustomEvent:class{constructor(type,options){Object.assign(this,{type,...options});}}});
|
const context=vm.createContext({BPQ_DEFAULT_LANGUAGE:defaultLanguage,navigator:{languages},localStorage:{getItem:k=>storage.get(k),setItem:(k,v)=>storage.set(k,v)},document:{documentElement:{lang:''},readyState:'loading',body:null,addEventListener(){},querySelectorAll:()=>[],dispatchEvent:e=>events.push(e)},addEventListener(){},CustomEvent:class{constructor(type,options){Object.assign(this,{type,...options});}}});
|
||||||
vm.runInContext(source,context);return {api:context.BPQI18n,document:context.document,storage,events};
|
vm.runInContext(source,context);return {api:context.BPQI18n,document:context.document,storage,events};
|
||||||
}
|
}
|
||||||
test('first visit chooses a concrete saved language from the browser, with English fallback',()=>{
|
test('first visit chooses a concrete saved language from the browser, with English fallback',()=>{
|
||||||
@@ -34,3 +34,5 @@ test('UI translations handle counters, statuses, decorative icons and dynamic va
|
|||||||
});
|
});
|
||||||
|
|
||||||
test('legacy Auto preference migrates to a concrete language',()=>{const {api,storage}=client(['en-US'],'auto');assert.equal(api.preference,'en');assert.equal(storage.get('bpq-language'),'en');});
|
test('legacy Auto preference migrates to a concrete language',()=>{const {api,storage}=client(['en-US'],'auto');assert.equal(api.preference,'en');assert.equal(storage.get('bpq-language'),'en');});
|
||||||
|
|
||||||
|
test('configured default language precedes browser detection, saved choice wins',()=>{assert.equal(client(['it-IT'],null,'en').api.language,'en');assert.equal(client(['en-US'],'it','en').api.language,'it');});
|
||||||
+3
-2
@@ -38,7 +38,8 @@ export async function prepareInstall(options={},dependencies={}){
|
|||||||
const catControl=options.catControl??(sameRadio&&saved.winlinkRadio?.catControl===true);
|
const catControl=options.catControl??(sameRadio&&saved.winlinkRadio?.catControl===true);
|
||||||
if(catControl&&(!radio||!modemFamily(radio.driver)))throw new Error('Winlink radio richiede un modem HF VARA, Pactor o ARDOP');
|
if(catControl&&(!radio||!modemFamily(radio.driver)))throw new Error('Winlink radio richiede un modem HF VARA, Pactor o ARDOP');
|
||||||
const vara=Boolean(radio&&/^VARA/i.test(radio.driver));
|
const vara=Boolean(radio&&/^VARA/i.test(radio.driver));
|
||||||
const config={...saved,nodeExe:process.execPath,bpqRoot:root,httpPort,port,radioPort:radio?.id??null,radioDriver:radio?.driver??null,sysopUser,forwardPeer,cmsPeer,varaSyslogPort:saved.varaSyslogPort??18514,varaLogPath:vara?(options.varaLogPath??(sameRadio?saved.varaLogPath:null)??null):null,winlinkRadio:{...(sameRadio?saved.winlinkRadio:{}),catControl:Boolean(catControl)}};
|
const language=options.language??previous.language??null;if(language!=null&&!['it','en'].includes(language))throw new Error('language deve essere it oppure en');
|
||||||
|
const config={...saved,...(language?{language}:{}),nodeExe:process.execPath,bpqRoot:root,httpPort,port,radioPort:radio?.id??null,radioDriver:radio?.driver??null,sysopUser,forwardPeer,cmsPeer,varaSyslogPort:saved.varaSyslogPort??18514,varaLogPath:vara?(options.varaLogPath??(sameRadio?saved.varaLogPath:null)??null):null,winlinkRadio:{...(sameRadio?saved.winlinkRadio:{}),catControl:Boolean(catControl)}};
|
||||||
if(!validPort(Number(config.varaSyslogPort)))throw new Error('Porta syslog VARA non valida');
|
if(!validPort(Number(config.varaSyslogPort)))throw new Error('Porta syslog VARA non valida');
|
||||||
const warnings=[];if(detected.radioPorts.length>1&&options.radioPort==null&&saved.radioPort==null)warnings.push('Più modem rilevati: selezionata la prima porta; usare -RadioPort per cambiarla.');
|
const warnings=[];if(detected.radioPorts.length>1&&options.radioPort==null&&saved.radioPort==null)warnings.push('Più modem rilevati: selezionata la prima porta; usare -RadioPort per cambiarla.');
|
||||||
if(detected.winlink&&!peers.includes(cmsPeer))warnings.push('Profilo CMS non presente: configurarlo in BPQ prima di usare il sync Winlink.');
|
if(detected.winlink&&!peers.includes(cmsPeer))warnings.push('Profilo CMS non presente: configurarlo in BPQ prima di usare il sync Winlink.');
|
||||||
@@ -51,7 +52,7 @@ export async function saveInstall(plan){
|
|||||||
let backup=null;try{backup=plan.configPath+'.'+new Date().toISOString().replace(/[:.]/g,'-')+'.backup';await copyFile(plan.configPath,backup);}catch(e){if(e.code!=='ENOENT')throw e;backup=null;}
|
let backup=null;try{backup=plan.configPath+'.'+new Date().toISOString().replace(/[:.]/g,'-')+'.backup';await copyFile(plan.configPath,backup);}catch(e){if(e.code!=='ENOENT')throw e;backup=null;}
|
||||||
await writeFile(plan.configPath+'.tmp',JSON.stringify(plan.config,null,2)+'\n');await rename(plan.configPath+'.tmp',plan.configPath);return {changed:true,backup};
|
await writeFile(plan.configPath+'.tmp',JSON.stringify(plan.config,null,2)+'\n');await rename(plan.configPath+'.tmp',plan.configPath);return {changed:true,backup};
|
||||||
}
|
}
|
||||||
export function parseArgs(args){const names={'bpq-root':'bpqRoot',port:'port','http-port':'httpPort','radio-port':'radioPort','sysop-user':'sysopUser','forward-peer':'forwardPeer','cms-peer':'cmsPeer','vara-log':'varaLogPath','config-path':'configPath'},options={};
|
export function parseArgs(args){const names={'bpq-root':'bpqRoot',port:'port','http-port':'httpPort','radio-port':'radioPort','sysop-user':'sysopUser','forward-peer':'forwardPeer','cms-peer':'cmsPeer','vara-log':'varaLogPath','config-path':'configPath',language:'language'},options={};
|
||||||
for(let i=0;i<args.length;i++){const n=args[i];if(n==='--check-only'){options.checkOnly=true;continue;}if(n==='--enable-radio-cat'||n==='--disable-radio-cat'){if(options.catControl!==undefined)throw new Error('Specificare una sola opzione CAT');options.catControl=n==='--enable-radio-cat';continue;}const key=names[n.slice(2)];if(!n.startsWith('--')||!key||args[i+1]===undefined||args[i+1].startsWith('--'))throw new Error('Opzione installer non valida o valore mancante');options[key]=args[++i];}return options;
|
for(let i=0;i<args.length;i++){const n=args[i];if(n==='--check-only'){options.checkOnly=true;continue;}if(n==='--enable-radio-cat'||n==='--disable-radio-cat'){if(options.catControl!==undefined)throw new Error('Specificare una sola opzione CAT');options.catControl=n==='--enable-radio-cat';continue;}const key=names[n.slice(2)];if(!n.startsWith('--')||!key||args[i+1]===undefined||args[i+1].startsWith('--'))throw new Error('Opzione installer non valida o valore mancante');options[key]=args[++i];}return options;
|
||||||
}
|
}
|
||||||
if(process.argv[1]&&samePath(process.argv[1],fileURLToPath(import.meta.url))){try{const options=parseArgs(process.argv.slice(2)),plan=await prepareInstall(options);console.log(JSON.stringify(plan.report,null,2));if(!options.checkOnly){const saved=await saveInstall(plan);console.log(saved.changed?'Configurazione salvata senza password. Backup precedente: '+(saved.backup||'prima installazione'):'Configurazione invariata.');}}catch(e){console.error('Installazione interrotta: '+e.message);process.exitCode=1;}}
|
if(process.argv[1]&&samePath(process.argv[1],fileURLToPath(import.meta.url))){try{const options=parseArgs(process.argv.slice(2)),plan=await prepareInstall(options);console.log(JSON.stringify(plan.report,null,2));if(!options.checkOnly){const saved=await saveInstall(plan);console.log(saved.changed?'Configurazione salvata senza password. Backup precedente: '+(saved.backup||'prima installazione'):'Configurazione invariata.');}}catch(e){console.error('Installazione interrotta: '+e.message);process.exitCode=1;}}
|
||||||
+5
-1
@@ -71,7 +71,7 @@ test('CLI parses explicit options and rejects typos or missing values',()=>{
|
|||||||
test('PowerShell installer CheckOnly supports paths with spaces and skips startup, task and firewall', {skip:process.platform!=='win32'},async t=>{
|
test('PowerShell installer CheckOnly supports paths with spaces and skips startup, task and firewall', {skip:process.platform!=='win32'},async t=>{
|
||||||
const f=await fixture(t);const fake=http.createServer((req,res)=>res.end('<a href=/Node/Ports.html>BPQ Ports</a>'));await new Promise(r=>fake.listen(0,'127.0.0.1',r));t.after(()=>new Promise(r=>fake.close(r)));await fs.writeFile(path.join(f.root,'BPQ32.cfg'),cfg().replace('8088',String(fake.address().port)));
|
const f=await fixture(t);const fake=http.createServer((req,res)=>res.end('<a href=/Node/Ports.html>BPQ Ports</a>'));await new Promise(r=>fake.listen(0,'127.0.0.1',r));t.after(()=>new Promise(r=>fake.close(r)));await fs.writeFile(path.join(f.root,'BPQ32.cfg'),cfg().replace('8088',String(fake.address().port)));
|
||||||
const env={...process.env,BPQ_CONSOLE_CONFIG:f.options.configPath};delete env.BPQ_ROOT;delete env.BPQ_CONSOLE_PORT;
|
const env={...process.env,BPQ_CONSOLE_CONFIG:f.options.configPath};delete env.BPQ_ROOT;delete env.BPQ_CONSOLE_PORT;
|
||||||
const result=await run('powershell.exe',['-NoProfile','-NonInteractive','-ExecutionPolicy','RemoteSigned','-File',path.resolve('Install.ps1'),'-NodeExe',process.execPath,'-BpqRoot',f.root,'-CheckOnly','-AutoStart','-EnableLAN','-Restart'],{env,windowsHide:true,timeout:20000});assert.match(result.stdout,/N9DEMO-7/);assert.ok(!result.stdout.includes('fixture-secret'));await assert.rejects(fs.stat(f.options.configPath),{code:'ENOENT'});
|
const result=await run('powershell.exe',['-NoProfile','-NonInteractive','-ExecutionPolicy','RemoteSigned','-File',path.resolve('Install.ps1'),'-NodeExe',process.execPath,'-BpqRoot',f.root,'-CheckOnly','-AutoStart','-EnableLAN','-Restart','-RadioPort','3','-SysopUser','operator','-Language','en','-ForwardPeer','N1PEER','-CmsPeer','CMS2'],{env,windowsHide:true,timeout:20000});assert.match(result.stdout,/N9DEMO-7/);const report=JSON.parse(result.stdout);assert.equal(report.selectedRadio,3);assert.equal(report.sysopUser,'operator');assert.ok(!result.stdout.includes('fixture-secret'));await assert.rejects(fs.stat(f.options.configPath),{code:'ENOENT'});
|
||||||
});
|
});
|
||||||
const freePort=async()=>{const s=net.createServer();await new Promise(r=>s.listen(0,'127.0.0.1',r));const p=s.address().port;await new Promise(r=>s.close(r));return p;};
|
const freePort=async()=>{const s=net.createServer();await new Promise(r=>s.listen(0,'127.0.0.1',r));const p=s.address().port;await new Promise(r=>s.close(r));return p;};
|
||||||
test('PowerShell startup confirms readiness, handles duplicate starts, restart and failed startup', {skip:process.platform!=='win32'},async t=>{
|
test('PowerShell startup confirms readiness, handles duplicate starts, restart and failed startup', {skip:process.platform!=='win32'},async t=>{
|
||||||
@@ -82,3 +82,7 @@ test('PowerShell startup confirms readiness, handles duplicate starts, restart a
|
|||||||
port=await freePort();await fs.writeFile(configFile,JSON.stringify({port,nodeExe:process.execPath}));await assert.rejects(start([]));assert.match((await start(['-Restart'])).stdout,/avviato/);pid=(await(await fetch('http://127.0.0.1:'+port+'/health')).json()).pid;
|
port=await freePort();await fs.writeFile(configFile,JSON.stringify({port,nodeExe:process.execPath}));await assert.rejects(start([]));assert.match((await start(['-Restart'])).stdout,/avviato/);pid=(await(await fetch('http://127.0.0.1:'+port+'/health')).json()).pid;
|
||||||
await fs.writeFile(path.join(f.dir,'server.mjs'),"throw new Error('fixture startup failure');");await assert.rejects(start(['-Restart']));pid=null;assert.match(await fs.readFile(path.join(f.dir,'server-error.log'),'utf8'),/fixture startup failure/);
|
await fs.writeFile(path.join(f.dir,'server.mjs'),"throw new Error('fixture startup failure');");await assert.rejects(start(['-Restart']));pid=null;assert.match(await fs.readFile(path.join(f.dir,'server-error.log'),'utf8'),/fixture startup failure/);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('installer language defaults can be selected, preserved and validated',async t=>{
|
||||||
|
const f=await fixture(t);const plan=await prepareInstall({...f.options,language:'en'},{probe});assert.equal(plan.config.language,'en');await saveInstall(plan);assert.equal((await prepareInstall(f.options,{probe})).config.language,'en');assert.equal((await prepareInstall({...f.options,language:'it'},{probe})).config.language,'it');await assert.rejects(prepareInstall({...f.options,language:'fr'},{probe}),/language/);assert.equal(parseArgs(['--language','en']).language,'en');
|
||||||
|
});
|
||||||
+1
-1
@@ -662,7 +662,7 @@ Invia un solo comando, massimo 1000 caratteri|Send one command, up to 1000 chara
|
|||||||
if(typeof document==='undefined')return;
|
if(typeof document==='undefined')return;
|
||||||
try{const saved=localStorage.getItem('bpq-language');if(['it','en'].includes(saved))preference=saved;}catch{}
|
try{const saved=localStorage.getItem('bpq-language');if(['it','en'].includes(saved))preference=saved;}catch{}
|
||||||
const browserLanguages=()=>navigator.languages?.length?navigator.languages:[navigator.language];
|
const browserLanguages=()=>navigator.languages?.length?navigator.languages:[navigator.language];
|
||||||
language=resolveLanguage(preference,browserLanguages());preference=language;try{localStorage.setItem('bpq-language',language);}catch{}document.documentElement.lang=language;
|
language=resolveLanguage(preference||globalThis.BPQ_DEFAULT_LANGUAGE,browserLanguages());preference=language;try{localStorage.setItem('bpq-language',language);}catch{}document.documentElement.lang=language;
|
||||||
const originals=new WeakMap(),attributes=new WeakMap();
|
const originals=new WeakMap(),attributes=new WeakMap();
|
||||||
// These are user/protocol data, never interface copy. Do not translate their labels or contents.
|
// These are user/protocol data, never interface copy. Do not translate their labels or contents.
|
||||||
const protectedContent='script,style,textarea,pre,code,[contenteditable],[data-no-i18n],.reader-body,.mail-subject,.mail-from,.mail-category,.reader-header h2,.reader-meta b,.chat-message-content p,.chat-message-meta strong,.chat-user-name,.chat-user b,.chat-user small,.room-button,#chat-room-name,.attachment-row b,#attachment-title,#delete-subject,.arrival-toast small,.side-station,.profile>div,.mission-heading h1,.mission-location,.modem-brand,#caller-call,#called-call,.service-call,#nodes,.wl-account,#wl-gateway-rows td:nth-child(2),#category option:not([value]),#terminal-output,.monitor-frame';
|
const protectedContent='script,style,textarea,pre,code,[contenteditable],[data-no-i18n],.reader-body,.mail-subject,.mail-from,.mail-category,.reader-header h2,.reader-meta b,.chat-message-content p,.chat-message-meta strong,.chat-user-name,.chat-user b,.chat-user small,.room-button,#chat-room-name,.attachment-row b,#attachment-title,#delete-subject,.arrival-toast small,.side-station,.profile>div,.mission-heading h1,.mission-location,.modem-brand,#caller-call,#called-call,.service-call,#nodes,.wl-account,#wl-gateway-rows td:nth-child(2),#category option:not([value]),#terminal-output,.monitor-frame';
|
||||||
|
|||||||
+1
-1
@@ -1,5 +1,5 @@
|
|||||||
<!doctype html>
|
<!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 Console</title><link rel="stylesheet" href="/i18n.css"><script src="/i18n.js"></script><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><link rel="stylesheet" href="/radio-control.css"><script defer src="/radio-control.js"></script><link rel="stylesheet" href="/sync-progress.css"><script type="module" src="/sync-progress.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 Console</title><link rel="stylesheet" href="/i18n.css"><script src="/ui-config.js"></script><script src="/i18n.js"></script><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><link rel="stylesheet" href="/radio-control.css"><script defer src="/radio-control.js"></script><link rel="stylesheet" href="/sync-progress.css"><script type="module" src="/sync-progress.js"></script></head>
|
||||||
<body>
|
<body>
|
||||||
<section id="login" class="login-screen"><div class="login-art"><h1>BPQ Console</h1><div class="login-byline" data-no-i18n>by IU2EUG</div><p>La tua stazione, in un unico pannello.</p></div><form id="login-form" class="login-card"><div class="login-brand"><span class="brand">BPQ Console</span><div class="login-byline" data-no-i18n>by IU2EUG</div></div><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></form></section>
|
<section id="login" class="login-screen"><div class="login-art"><h1>BPQ Console</h1><div class="login-byline" data-no-i18n>by IU2EUG</div><p>La tua stazione, in un unico pannello.</p></div><form id="login-form" class="login-card"><div class="login-brand"><span class="brand">BPQ Console</span><div class="login-byline" data-no-i18n>by IU2EUG</div></div><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></form></section>
|
||||||
<div id="shell" hidden><aside class="sidebar"><a class="brand" href="#home">BPQ Console</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>
|
<div id="shell" hidden><aside class="sidebar"><a class="brand" href="#home">BPQ Console</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>
|
||||||
|
|||||||
+3
-2
@@ -36,7 +36,7 @@ const upstream='http://127.0.0.1:'+config.httpPort;
|
|||||||
const sessions=new Map(), attempts=new Map();
|
const sessions=new Map(), attempts=new Map();
|
||||||
const port=config.port;
|
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 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});
|
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 monitor=new Monitor(credentials,{port:config.monitorPort});
|
||||||
const varaRate=config.features.vara?new VaraRate(config.varaSyslogPort||18514):null;
|
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;
|
let telemetry={current:null,history:[]},telemetryBusy=false,priorTraffic=null,priorCpu=null,varaCpu=null,priorVaraCpu=null;
|
||||||
@@ -115,6 +115,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;}
|
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'");
|
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);
|
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(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(req.method==='POST'&&req.headers.origin!=='http://'+host){json(res,403,{error:'Origine non autorizzata'});return;}
|
||||||
if(url.pathname==='/api/login'&&req.method==='POST'){
|
if(url.pathname==='/api/login'&&req.method==='POST'){
|
||||||
@@ -128,7 +129,7 @@ const server=http.createServer(async(req,res)=>{
|
|||||||
if(req.method==='POST'&&!equal(req.headers['x-csrf-token']||'',user.csrf)){json(res,403,{error:'Sessione non valida. Ricarica la pagina.'});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(url.pathname.startsWith('/api/terminal')){
|
||||||
if(!config.telnetPort)throw new Error('Porta Telnet BPQ non configurata');
|
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});
|
if(!user.terminal)user.terminal=new Terminal(async()=>{const c=await loadConfig();return c.sysop;},{port:config.telnetPort,...config.telnetPrompts});
|
||||||
const terminal=user.terminal;
|
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'&&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/connect'&&req.method==='POST'){json(res,200,await terminal.connect());return;}
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
// 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);}
|
||||||
|
}
|
||||||
|
|
||||||
|
// BPQ can send a custom CTEXT without a node prompt. Wait for the banner to
|
||||||
|
// settle before declaring success; repeated credential prompts mean rejection.
|
||||||
|
export class TelnetLogin {
|
||||||
|
constructor(socket,credentials,options,ready){
|
||||||
|
this.socket=socket;this.credentials=credentials;this.options=options;this.ready=ready;this.stage=0;this.buffer='';this.closed=false;
|
||||||
|
this.deadline=setTimeout(()=>this.fail('Accesso Telnet non confermato'),15000);this.deadline.unref();
|
||||||
|
}
|
||||||
|
hasPrompt(text,kind){
|
||||||
|
const custom=this.options[kind+'Prompt'];
|
||||||
|
return !!(custom&&text.toLowerCase().includes(custom.toLowerCase()))||(kind==='login'?/(?:^|[\r\n])\s*(?:Username|Login|User)\s*:/i:/\bPassword\s*:/i).test(text);
|
||||||
|
}
|
||||||
|
clean(text){
|
||||||
|
const password=this.credentials?.password;
|
||||||
|
if(!password)return text;let clean=text.split(password).join('');
|
||||||
|
for(let n=password.length-1;n>0;n--)if(clean.endsWith(password.slice(0,n))){clean=clean.slice(0,-n);break;}
|
||||||
|
return clean;
|
||||||
|
}
|
||||||
|
read(text){
|
||||||
|
if(this.closed||!text)return;
|
||||||
|
this.buffer+=text;if(this.buffer.length>12000){this.fail('Accesso Telnet non confermato');return;}
|
||||||
|
if(this.stage===0&&this.hasPrompt(this.buffer,'login')){this.buffer='';this.stage=1;this.socket.write(this.credentials.user+'\r');return;}
|
||||||
|
if(this.stage===1&&this.hasPrompt(this.buffer,'password')){this.buffer='';this.stage=2;this.socket.write(this.credentials.password+'\r');return;}
|
||||||
|
if(this.stage!==2)return;
|
||||||
|
clearTimeout(this.quiet);
|
||||||
|
const clean=this.clean(this.buffer);
|
||||||
|
if(this.hasPrompt(clean,'login')||this.hasPrompt(clean,'password')||/\b(?:invalid|incorrect|denied|authentication failed|access rejected)\b/i.test(clean)){this.fail('Accesso rifiutato');return;}
|
||||||
|
if(!clean.trim())return;
|
||||||
|
this.quiet=setTimeout(()=>{
|
||||||
|
if(this.closed||this.socket.destroyed)return;
|
||||||
|
const banner=this.clean(this.buffer).trimStart();this.close();this.ready(banner);
|
||||||
|
},400);this.quiet.unref();
|
||||||
|
}
|
||||||
|
fail(message){this.close();this.socket.destroy(new Error(message));}
|
||||||
|
close(){this.closed=true;clearTimeout(this.quiet);clearTimeout(this.deadline);this.buffer='';this.credentials=null;}
|
||||||
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
import test from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import net from 'node:net';
|
||||||
|
import {once} from 'node:events';
|
||||||
|
import {Terminal} from './terminal.mjs';
|
||||||
|
import {Chat} from './chat.mjs';
|
||||||
|
import {TelnetLogin} from './telnet-login.mjs';
|
||||||
|
import {parseConfig} from './config.mjs';
|
||||||
|
|
||||||
|
const sleep=ms=>new Promise(resolve=>setTimeout(resolve,ms));
|
||||||
|
async function until(fn){for(let n=0;n<200&&!fn();n++)await sleep(10);assert.ok(fn(),'Expected Telnet state was not reached');}
|
||||||
|
async function fixture(t,Class,{login='Login:',password='Password:',reject=null,prompts={},brace=false}={}){
|
||||||
|
const sockets=new Set(),commands=[];let lastBanner=0,chatAt=0;
|
||||||
|
const server=net.createServer(socket=>{
|
||||||
|
sockets.add(socket);socket.on('close',()=>sockets.delete(socket));socket.on('error',()=>{});
|
||||||
|
socket.write(login.slice(0,2));setImmediate(()=>socket.write(login.slice(2)));
|
||||||
|
let stage=0,buffer='';socket.on('data',chunk=>{
|
||||||
|
buffer+=chunk;let end;while((end=buffer.indexOf('\r'))>=0){const line=buffer.slice(0,end);buffer=buffer.slice(end+1);commands.push(line);
|
||||||
|
if(stage++===0)socket.write(password);
|
||||||
|
else if(stage===2){
|
||||||
|
socket.write('fixture-');setTimeout(()=>{
|
||||||
|
if(socket.destroyed)return;socket.write('secret\r\n');
|
||||||
|
if(reject){socket.write(reject);return;}
|
||||||
|
socket.write('Custom station banner\r\n');
|
||||||
|
setTimeout(()=>{if(!socket.destroyed){lastBanner=Date.now();socket.write(brace?'BOLHF:IW2OHX-15}':'IW2OHX-5 Idle\r\n');}},35);
|
||||||
|
},20);
|
||||||
|
}else if(line==='CHAT'){chatAt=Date.now();socket.write('[BPQChatServer-6.0]\r\n');}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});server.listen(0,'127.0.0.1');await once(server,'listening');
|
||||||
|
const client=new Class(async()=>({user:'fixture',password:'fixture-secret'}),{port:server.address().port,...prompts});
|
||||||
|
t.after(async()=>{if(Class===Terminal)client.close();else{client.disconnect();clearInterval(client.timer);}for(const socket of sockets)socket.destroy();await new Promise(resolve=>server.close(resolve));});
|
||||||
|
return {client,commands,get lastBanner(){return lastBanner},get chatAt(){return chatAt}};
|
||||||
|
}
|
||||||
|
|
||||||
|
for(const Class of [Terminal,Chat])for(const login of ['Username:','Login:','User:'])test(`${Class.name} accepts ${login} and a custom CTEXT without Welcome or a prompt`,async t=>{
|
||||||
|
const f=await fixture(t,Class,{login});await f.client.connect();await until(()=>f.client.state==='online');
|
||||||
|
assert.deepEqual(f.commands.slice(0,2),['fixture','fixture-secret']);
|
||||||
|
const events=JSON.stringify(f.client.snapshot().events);assert.ok(!events.includes('fixture-secret'));assert.ok(!events.includes('fixture-'));
|
||||||
|
if(Class===Chat){assert.ok(f.chatAt-f.lastBanner>=380);assert.ok(!events.includes('Custom station banner'));assert.ok(!events.includes('Idle'));}
|
||||||
|
else assert.ok(events.includes('Custom station banner'));
|
||||||
|
});
|
||||||
|
test('terminal accepts a BPQ node prompt ending with a closing brace',async t=>{
|
||||||
|
const {client}=await fixture(t,Terminal,{brace:true});await client.connect();await until(()=>client.state==='online');assert.ok(client.events.some(e=>e.text.includes('BOLHF:IW2OHX-15}')));
|
||||||
|
});
|
||||||
|
for(const Class of [Terminal,Chat])for(const reject of ['Login:','Password:','Invalid password'])test(`${Class.name} rejects a repeated credential prompt or explicit denial: ${reject}`,async t=>{
|
||||||
|
const {client,commands}=await fixture(t,Class,{reject});await client.connect();await until(()=>client.state==='error');assert.equal(commands.includes('CHAT'),false);assert.ok(!JSON.stringify(client.snapshot()).includes('fixture-secret'));
|
||||||
|
});
|
||||||
|
test('both clients use literal configured prompts, including regex punctuation',async t=>{
|
||||||
|
for(const Class of [Terminal,Chat]){
|
||||||
|
const {client}=await fixture(t,Class,{login:'Identita [nodo]? ',password:'Chiave (accesso)? ',prompts:{loginPrompt:'Identita [nodo]?',passwordPrompt:'Chiave (accesso)?'}});
|
||||||
|
await client.connect();await until(()=>client.state==='online');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
test('password echo alone and fragmented secret prefixes cannot confirm login or leak output',async()=>{
|
||||||
|
const writes=[],socket={destroyed:false,write:s=>writes.push(s),destroy(){this.destroyed=true}},ready=[];
|
||||||
|
const login=new TelnetLogin(socket,{user:'demo',password:'fixture-secret'},{},text=>ready.push(text));
|
||||||
|
try{login.read('Login:');login.read('Password:');login.read('fixture-');await sleep(430);assert.equal(ready.length,0);login.read('secret\r\n');await sleep(430);assert.equal(ready.length,0);login.read('Custom banner');await sleep(430);assert.deepEqual(ready,['Custom banner']);}
|
||||||
|
finally{login.close();}
|
||||||
|
});
|
||||||
|
test('closing during the banner prevents a delayed CHAT command',async t=>{
|
||||||
|
const {client,commands}=await fixture(t,Chat);await client.connect();await until(()=>commands.includes('fixture-secret'));client.disconnect();await sleep(500);assert.equal(commands.includes('CHAT'),false);
|
||||||
|
});
|
||||||
|
test('Telnet prompts are read from the Telnet port only; PASSWORD is not a prompt',()=>{
|
||||||
|
const cfg=parseConfig('PORT\nDRIVER=OTHER\nLOGINPROMPT=wrong\nENDPORT\nPORT\nDRIVER=Telnet.dll\nLOGINPROMPT=Identita [nodo]?\nPASSWORDPROMPT=Chiave (accesso)?\nPASSWORD=not-a-prompt\nENDPORT');
|
||||||
|
assert.deepEqual(cfg.telnetPrompts,{loginPrompt:'Identita [nodo]?',passwordPrompt:'Chiave (accesso)?'});
|
||||||
|
});
|
||||||
+9
-20
@@ -1,35 +1,24 @@
|
|||||||
import net from 'node:net';
|
import net from 'node:net';
|
||||||
import {StringDecoder} from 'node:string_decoder';
|
import {StringDecoder} from 'node:string_decoder';
|
||||||
|
|
||||||
// Telnet commands may be split across TCP packets, including subnegotiations.
|
import {TelnetText,TelnetLogin} from './telnet-login.mjs';
|
||||||
export class TelnetText {
|
export {TelnetText} from './telnet-login.mjs';
|
||||||
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 {
|
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();}
|
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;}
|
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};}
|
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);
|
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.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('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('error',e=>{if(this.socket!==socket)return;this.state='error';this.error=['Accesso rifiutato','Accesso Telnet non confermato'].includes(e.message)?e.message:'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('close',()=>{if(this.socket!==socket)return;this.login?.close();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);
|
this.login=new TelnetLogin(socket,credentials,this.options,text=>{if(this.socket!==socket)return;this.stage=3;this.state='online';socket.setTimeout(0);this.output(text);});
|
||||||
if(this.stage===0&&/Username:/i.test(this.auth)){socket.write(credentials.user+'\r');this.stage=1;this.auth='';return;}
|
socket.on('data',chunk=>{if(this.socket!==socket)return;const text=this.decoder.write(telnet.read(chunk));if(this.stage<3){this.login.read(text);return;}this.output(text);});return this.snapshot();}
|
||||||
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;}
|
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(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;
|
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);}
|
}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');}
|
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');}
|
disconnect(reason='Disconnessione richiesta'){this.login?.close();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);}
|
close(){this.disconnect();clearInterval(this.timer);}
|
||||||
}
|
}
|
||||||
@@ -49,12 +49,12 @@ test('generic PACTOR station runs without VARA, chat, monitor or BBS',async()=>{
|
|||||||
await new Promise(r=>upstream.listen(0,'127.0.0.1',r));
|
await new Promise(r=>upstream.listen(0,'127.0.0.1',r));
|
||||||
const httpPort=upstream.address().port;
|
const httpPort=upstream.address().port;
|
||||||
const cfg=['NODECALL=N9DEMO-7','NODEALIAS=DEMO','LOCATOR=AA00AA','PORT','PORTNUM=3','ID=PACTOR modem','DRIVER=SCSPACTOR','ENDPORT','PORT','PORTNUM=5','DRIVER=TELNET','HTTPPORT='+httpPort,'USER=admin,fixture,N9DEMO,sysop','ENDPORT'].join('\n');
|
const cfg=['NODECALL=N9DEMO-7','NODEALIAS=DEMO','LOCATOR=AA00AA','PORT','PORTNUM=3','ID=PACTOR modem','DRIVER=SCSPACTOR','ENDPORT','PORT','PORTNUM=5','DRIVER=TELNET','HTTPPORT='+httpPort,'USER=admin,fixture,N9DEMO,sysop','ENDPORT'].join('\n');
|
||||||
await fs.writeFile(path.join(tmp,'BPQ32.cfg'),cfg);await fs.writeFile(path.join(tmp,'console.config.json'),JSON.stringify({bpqRoot:tmp,httpPort,port:18991}));
|
await fs.writeFile(path.join(tmp,'BPQ32.cfg'),cfg);await fs.writeFile(path.join(tmp,'console.config.json'),JSON.stringify({bpqRoot:tmp,httpPort,port:18991,language:"en"}));
|
||||||
const parsed=parseConfig(cfg);assert.equal(parsed.radioPorts[0].id,3);assert.equal(parsed.call,'N9DEMO');
|
const parsed=parseConfig(cfg);assert.equal(parsed.radioPorts[0].id,3);assert.equal(parsed.call,'N9DEMO');
|
||||||
const child=cp.spawn(process.execPath,['server.mjs'],{cwd:process.cwd(),env:{...process.env,BPQ_ROOT:tmp,BPQ_CONSOLE_CONFIG:path.join(tmp,'console.config.json'),BPQ_CONSOLE_PORT:'18991'},windowsHide:true,stdio:['ignore','pipe','pipe']});
|
const child=cp.spawn(process.execPath,['server.mjs'],{cwd:process.cwd(),env:{...process.env,BPQ_ROOT:tmp,BPQ_CONSOLE_CONFIG:path.join(tmp,'console.config.json'),BPQ_CONSOLE_PORT:'18991'},windowsHide:true,stdio:['ignore','pipe','pipe']});
|
||||||
try{
|
try{
|
||||||
await new Promise((resolve,reject)=>{const timeout=setTimeout(()=>reject(new Error('Server fixture timeout')),8000);child.stdout.once('data',()=>{clearTimeout(timeout);resolve()});child.once('exit',code=>{clearTimeout(timeout);reject(new Error('Server fixture exited '+code))})});
|
await new Promise((resolve,reject)=>{const timeout=setTimeout(()=>reject(new Error('Server fixture timeout')),8000);child.stdout.once('data',()=>{clearTimeout(timeout);resolve()});child.once('exit',code=>{clearTimeout(timeout);reject(new Error('Server fixture exited '+code))})});
|
||||||
const base='http://127.0.0.1:18991';const health=await fetch(base+'/health');assert.equal(health.status,200);assert.equal((await health.json()).service,'bpq-console');const login=await fetch(base+'/api/login',{method:'POST',headers:{Origin:base,'Content-Type':'application/json'},body:JSON.stringify({user:'admin',password:'fixture'})});assert.equal(login.status,200);const user=await login.json();assert.equal(user.call,'N9DEMO');assert.equal(user.config.features.vara,false);assert.equal(user.config.features.bbs,false);assert.equal(user.config.radio.id,3);assert.equal(JSON.stringify(user.config).includes('fixture'),false);
|
const base='http://127.0.0.1:18991';const uiConfig=await fetch(base+'/ui-config.js');assert.equal(uiConfig.status,200);assert.equal(await uiConfig.text(),'globalThis.BPQ_DEFAULT_LANGUAGE="en";');const health=await fetch(base+'/health');assert.equal(health.status,200);assert.equal((await health.json()).service,'bpq-console');const login=await fetch(base+'/api/login',{method:'POST',headers:{Origin:base,'Content-Type':'application/json'},body:JSON.stringify({user:'admin',password:'fixture'})});assert.equal(login.status,200);const user=await login.json();assert.equal(user.call,'N9DEMO');assert.equal(user.config.features.vara,false);assert.equal(user.config.features.bbs,false);assert.equal(user.config.radio.id,3);assert.equal(JSON.stringify(user.config).includes('fixture'),false);
|
||||||
const headers={Cookie:login.headers.get('set-cookie').split(';')[0]};const logbook=await fetch(base+'/api/journal',{headers});assert.equal(logbook.status,200);assert.deepEqual((await logbook.json()).sessions,[]);const denied=await fetch(base+'/api/stations/location',{method:'POST',headers:{...headers,Origin:base,'Content-Type':'application/json'},body:JSON.stringify({call:'N3TEST',locator:'JN45NN'})});assert.equal(denied.status,403);assert.equal((await fetch(base+'/api/terminal',{headers})).status,409);assert.equal((await fetch(base+'/api/chat',{headers})).status,409);assert.equal((await fetch(base+'/api/monitor',{headers})).status,409);assert.equal((await fetch(base+'/api/winlink',{headers})).status,409);
|
const headers={Cookie:login.headers.get('set-cookie').split(';')[0]};const logbook=await fetch(base+'/api/journal',{headers});assert.equal(logbook.status,200);assert.deepEqual((await logbook.json()).sessions,[]);const denied=await fetch(base+'/api/stations/location',{method:'POST',headers:{...headers,Origin:base,'Content-Type':'application/json'},body:JSON.stringify({call:'N3TEST',locator:'JN45NN'})});assert.equal(denied.status,403);assert.equal((await fetch(base+'/api/terminal',{headers})).status,409);assert.equal((await fetch(base+'/api/chat',{headers})).status,409);assert.equal((await fetch(base+'/api/monitor',{headers})).status,409);assert.equal((await fetch(base+'/api/winlink',{headers})).status,409);
|
||||||
await new Promise(r=>setTimeout(r,1200));const telemetry=await (await fetch(base+'/api/telemetry',{headers})).json();assert.equal(telemetry.current.available,true);assert.equal(telemetry.current.nativeRate.listening,false);assert.equal(telemetry.current.varaCpu,null);assert.equal(telemetry.current.sent,12);
|
await new Promise(r=>setTimeout(r,1200));const telemetry=await (await fetch(base+'/api/telemetry',{headers})).json();assert.equal(telemetry.current.available,true);assert.equal(telemetry.current.nativeRate.listening,false);assert.equal(telemetry.current.varaCpu,null);assert.equal(telemetry.current.sent,12);
|
||||||
const dash=await (await fetch(base+'/api/dashboard',{headers})).json();assert.equal(dash.counts.messages,0);
|
const dash=await (await fetch(base+'/api/dashboard',{headers})).json();assert.equal(dash.counts.messages,0);
|
||||||
|
|||||||
Reference in new issue
Block a user