From 2b00b1cbbdfd213b5e373cb5e08fe759f9a4eaa6 Mon Sep 17 00:00:00 2001 From: alberto Date: Sat, 17 Oct 2026 14:14:16 +0200 Subject: [PATCH] Support custom BPQ Telnet prompts and banners, fix installer arguments --- Install.ps1 | 6 ++-- README.md | 6 +++- chat.mjs | 22 +++++++++----- config.mjs | 5 ++-- i18n.test.mjs | 6 ++-- install.mjs | 5 ++-- install.test.mjs | 6 +++- public/i18n.js | 2 +- public/index.html | 2 +- server.mjs | 5 ++-- telnet-login.mjs | 47 ++++++++++++++++++++++++++++++ telnet-login.test.mjs | 67 +++++++++++++++++++++++++++++++++++++++++++ terminal.mjs | 29 ++++++------------- test.mjs | 4 +-- 14 files changed, 168 insertions(+), 44 deletions(-) create mode 100644 telnet-login.mjs create mode 100644 telnet-login.test.mjs diff --git a/Install.ps1 b/Install.ps1 index d8c9afc..f441ae1 100644 --- a/Install.ps1 +++ b/Install.ps1 @@ -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' 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.'} @@ -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."}} } $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'} -foreach($name in $mapping.Keys){if($PSBoundParameters.ContainsKey($name)){$nodeArgs+=@('--'+$mapping[$name],[string](Get-Variable -Name $name -ValueOnly))}} +$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))}} 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($DisableRadioCAT){$nodeArgs+='--disable-radio-cat'} diff --git a/README.md b/README.md index c668969..e9ed02b 100644 --- a/README.md +++ b/README.md @@ -4,10 +4,14 @@ A local web dashboard for BPQ32: node status, BBS, Winlink, forwarding, chat, tr ## 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. +## 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 - Windows and Windows PowerShell 5.1 or later. diff --git a/chat.mjs b/chat.mjs index b8f605e..9d38fab 100644 --- a/chat.mjs +++ b/chat.mjs @@ -1,18 +1,26 @@ import net from 'node:net'; 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 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();} 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};} - 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')}); - 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.stage===0&&/Username:/i.test(this.authBuffer)){this.write(user);this.stage=1;this.authBuffer='';return;} - if(this.stage===1&&/Password:/i.test(this.authBuffer)){this.write(password);this.stage=2;this.authBuffer='';return;} - 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;} - 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());}); + 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.users=[];this.links=[];this.events=[];this.section='';this.stage=0;this.buffer='';this.decoder=new StringDecoder('utf8'); + 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); + 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();} + 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(/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);} 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);} - 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';} } diff --git a/config.mjs b/config.mjs index f96122e..0b587d0 100644 --- a/config.mjs +++ b/config.mjs @@ -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 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; - 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||{}; for(const p of ports)delete p.settings; const radioPorts=ports.filter(p=>!/TELNET|AXIP|LOOPBACK/i.test(p.driver)&&p.driver); 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(){ 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;} 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'); + 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')); 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'); diff --git a/i18n.test.mjs b/i18n.test.mjs index df6f88b..c78be97 100644 --- a/i18n.test.mjs +++ b/i18n.test.mjs @@ -3,9 +3,9 @@ import assert from 'node:assert/strict'; import vm from 'node:vm'; import {readFileSync} from 'node:fs'; 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 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}; } 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('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');}); diff --git a/install.mjs b/install.mjs index b6d40dd..84d7804 100644 --- a/install.mjs +++ b/install.mjs @@ -38,7 +38,8 @@ export async function prepareInstall(options={},dependencies={}){ 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'); 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'); 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.'); @@ -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;} 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{ 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('BPQ Ports'));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 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;}; 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; 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'); +}); diff --git a/public/i18n.js b/public/i18n.js index 52a33e5..ff6a565 100644 --- a/public/i18n.js +++ b/public/i18n.js @@ -662,7 +662,7 @@ Invia un solo comando, massimo 1000 caratteri|Send one command, up to 1000 chara if(typeof document==='undefined')return; try{const saved=localStorage.getItem('bpq-language');if(['it','en'].includes(saved))preference=saved;}catch{} 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(); // 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'; diff --git a/public/index.html b/public/index.html index 6129f7f..74e58ed 100644 --- a/public/index.html +++ b/public/index.html @@ -1,5 +1,5 @@ -BPQ Console +BPQ Console