Support multiple sysops and bulletin comments; complete UI translations
Allow native SYSOP accounts to sign in independently, with an optional sysopUsers allow-list and isolated browser sessions. Keep station services on the configured service account. Add public bulletin comments that preserve category and distribution, alongside private replies to the author. Complete APRS and dynamic status translations and handle decorated button labels correctly. Document configuration and reply behavior. Add authentication, installer, bulletin reply and translation regression coverage.
This commit is contained in:
1 parent
33f1294405
commit
2ef3c25eb3
16 files changed
+298
-23
No files matched your search
@@ -8,9 +8,30 @@ Use the Italian / UK flag switch in the login screen or dashboard header to sele
|
||||
|
||||
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.
|
||||
|
||||
## Sysop accounts
|
||||
|
||||
Every Telnet `USER=` account with the `SYSOP` flag in `BPQ32.cfg` can sign in with its own username and password. Usernames are case-insensitive; passwords are case-sensitive. Normal BPQ users cannot sign in. Each browser session has its own identity, cookie and CSRF token; signing out of one session leaves other sessions active. The profile shows the signed-in user's callsign.
|
||||
|
||||
`sysopUser` in `console.config.json` selects the station's service account. Terminal connections, the shared Chat, Monitor and native BBS operations continue to use that account. All authorised sysops administer the same station, BBS and Winlink mailbox; logging in with another callsign does not create a separate mailbox or change the station identity.
|
||||
|
||||
To restrict Console access to particular native sysops, add the optional `sysopUsers` allow-list:
|
||||
|
||||
```json
|
||||
{
|
||||
"sysopUser": "admin",
|
||||
"sysopUsers": ["admin", "Marco"]
|
||||
}
|
||||
```
|
||||
|
||||
Use existing BPQ usernames, not callsigns. Every listed account must already have the native `SYSOP` flag. Entries are case-insensitive; credentials remain exclusively in `BPQ32.cfg`. Omitting `sysopUsers` allows all native sysops; an empty array allows nobody. Invalid lists stop startup/installation instead of being ignored. Restart BPQ Console after changing the list; BPQ does not need a restart. Reinstallation preserves the list for the same station folder and resets it when installing against another station.
|
||||
|
||||
## Bulletin comments and private replies
|
||||
|
||||
The BBS reader offers **Comment** for bulletins: it creates a new bulletin (`B`) addressed to the original category and distribution, for example `NEWS@WW`. **Reply** creates a personal message (`P`) addressed to the author. Personal messages only show Reply. Both actions open an editable draft with the original subject prefixed by `Re:` and the quoted text; nothing is published until Save and queue is selected. Comments use BPQ's normal bulletin forwarding rules and do not modify the original message.
|
||||
|
||||
## Message deletion
|
||||
|
||||
Deleting BBS or Winlink messages requires the configured Console sysop login and CSRF token. The Console opens a fresh BPQ WebMail session, issues the native delete action and verifies that the message disappeared or has status `K`. If WebMail rejects deleting another author’s bulletin, the authenticated sysop Console uses BPQ’s local administrative message action, preserving the other message fields and changing only status to `K`. BPQ updates its own database and forwarding flags. No account flags are changed. Already deleted messages are handled safely; failures are displayed inside the confirmation dialog.
|
||||
Deleting BBS or Winlink messages requires an authorised Console sysop login and that session's CSRF token. The Console opens a fresh BPQ WebMail session, issues the native delete action and verifies that the message disappeared or has status `K`. If WebMail rejects deleting another author’s bulletin, the authenticated sysop Console uses BPQ’s local administrative message action, preserving the other message fields and changing only status to `K`. BPQ updates its own database and forwarding flags. No account flags are changed. Already deleted messages are handled safely; failures are displayed inside the confirmation dialog.
|
||||
|
||||
## Winlink attachments
|
||||
|
||||
@@ -27,7 +48,7 @@ Terminal and Chat read `LOGINPROMPT` and `PASSWORDPROMPT` from the Telnet port i
|
||||
- Windows and Windows PowerShell 5.1 or later.
|
||||
- Node.js 20 or later. A portable `node.exe` can be selected with `-NodeExe`.
|
||||
- BPQ32 installed and running, with `HTTPPORT` configured in its Telnet driver.
|
||||
- A Telnet `USER` with the `sysop` role. The panel accepts the selected sysop account; its password stays in `BPQ32.cfg`.
|
||||
- A Telnet `USER` with the `sysop` role. The panel accepts native SYSOP accounts, subject to the optional `sysopUsers` allow-list; passwords stay in `BPQ32.cfg`.
|
||||
- Optional: BPQMail for BBS/Winlink, BPQChat and `TCPPORT` for chat, `FBBPORT` for the monitor. The terminal only needs `TCPPORT`.
|
||||
|
||||
Service detection recognises the `BBS` and `CHAT` application command names, case-insensitively. Those applications must actually be running to use their pages. The installer does not install BPQ, configure a modem, change radio frequencies or create forwarding partners.
|
||||
@@ -54,7 +75,7 @@ Install and start:
|
||||
.\Install.ps1
|
||||
```
|
||||
|
||||
Open **http://127.0.0.1:8090** and sign in with the selected BPQ Telnet sysop account. No `npm install` or build step is required.
|
||||
Open **http://127.0.0.1:8090** and sign in with an authorised BPQ Telnet SYSOP account. No `npm install` or build step is required.
|
||||
|
||||
Detection uses an explicit `-BpqRoot`, `BPQ_ROOT`, the previously saved data folder, `%APPDATA%\BPQ32`, or the folders of running BPQ processes. The HTTP check must identify BPQ before any configuration is written. `-CheckOnly` never saves configuration, starts the panel, registers a task or changes the firewall, even if other switches are present.
|
||||
|
||||
@@ -70,7 +91,7 @@ Explicit settings:
|
||||
| `-Port` | Web panel port, 1024–65535; default 8090 on first install. |
|
||||
| `-HttpPort` | BPQ HTTP port; defaults to the Telnet driver setting. Must differ from the panel port. |
|
||||
| `-RadioPort` | Existing BPQ radio port number. The first is selected initially; multiple modems produce a warning. |
|
||||
| `-SysopUser` | Existing sysop user; defaults to the first on initial installation. |
|
||||
| `-SysopUser` | Native sysop account used by Terminal, Chat and station services; defaults to the first on initial installation. Console logins are controlled separately by `sysopUsers`. |
|
||||
| `-ForwardPeer` | Existing BBS forwarding partner for the dashboard shortcut. No partner is created automatically. |
|
||||
| `-CmsPeer` | Existing CMS forwarding profile; defaults to `RMS`. |
|
||||
| `-NodeExe` | Full path to a Node.js 20+ `node.exe`. Saved for future startup. |
|
||||
|
||||
@@ -2,6 +2,6 @@ export function decode(s){return s.replace(/&#(\d+);/g,(_,n)=>String.fromCodePoi
|
||||
export function plain(html){return decode(html.replace(/<script[\s\S]*?<\/script>/gi,'').replace(/<style[\s\S]*?<\/style>/gi,'').replace(/<[^>]+>/g,' ')).replace(/\s+/g,' ').trim();}
|
||||
export function parseMessages(html){const result=[];const regex=/<a\s+href=\/WebMail\/WM\?[^>&\s]+&(\d+)>[^<]+<\/a>([^\r\n<]+)/gi;for(const m of html.matchAll(regex)){const line=m[2];const a=line.match(/^\s*(\S+)\s+([BPT])([A-Z$])\s+(\d+)\s(.{7})\s(.{7})\s(.{7})(.*)$/);if(a){result.push({id:Number(m[1]),date:a[1],type:a[2],status:a[3],size:Number(a[4]),to:a[5].trim(),via:a[6].trim(),from:a[7].trim(),subject:decode(a[8].trim())});continue;}const header=line.match(/^\s*(\S+)\s+([BPT])([A-Z$])\s+(\d+) (.{8})(.*)$/);if(!header)continue;const tail=header[6].match(/^(.*?)([A-Z0-9]{1,6}) {2,}(.*)$/);if(tail)result.push({id:Number(m[1]),date:header[1],type:header[2],status:header[3],size:Number(header[4]),to:header[5].trim(),via:tail[1].trim(),from:tail[2],subject:decode(tail[3].trim()),needsMetadata:true});}return result;}
|
||||
export function parseRoutes(html){return [...html.matchAll(/<tr>([\s\S]*?)<\/tr>/gi)].flatMap(m=>{const cells=[...m[1].matchAll(/<td[^>]*>([\s\S]*?)<\/td>/gi)].map(c=>plain(c[1]));if(cells.length<12)return [];return [{port:cells[0].replace('>',''),active:cells[0].startsWith('>'),call:cells[1],quality:Number(cells[2]),nodes:Number(cells[3]),frames:Number(cells[4]),retries:Number(cells[5]),heard:cells[9],queued:Number(cells[10])}];});}
|
||||
export function parseMessage(html){const m=html.match(/<textarea[^>]*>([\s\S]*?)<\/textarea>/i);if(!m)return null;const text=decode(m[1]).replace(/\r\n|\r/g,'\n');const header={},first=text.indexOf('\n\n');for(const l of text.slice(0,first).split('\n')){const sep=l.indexOf(':');if(sep>0)header[l.slice(0,sep)]=l.slice(sep+1).trim();}return {from:header.From||'',to:header.To||'',subject:header.Title||'',date:header['Date/Time']||'',bid:header.Bid||'',type:header['Type/Status']?.[0]||'',text:first>=0?text.slice(first+2):text};}
|
||||
export function parseMessage(html){const m=html.match(/<textarea[^>]*>([\s\S]*?)<\/textarea>/i);if(!m)return null;const text=decode(m[1]).replace(/\r\n|\r/g,'\n');const header={},first=text.indexOf('\n\n');for(const l of text.slice(0,first).split('\n')){const sep=l.indexOf(':');if(sep>0)header[l.slice(0,sep)]=l.slice(sep+1).trim();}return {from:header.From||'',to:header.To||'',via:header.Via||header.VIA||'',subject:header.Title||'',date:header['Date/Time']||'',bid:header.Bid||'',type:header['Type/Status']?.[0]||'',text:first>=0?text.slice(first+2):text};}
|
||||
export function bpqTimestamp(value,reference=new Date()) {const m=String(value||'').match(/^(\d{1,2})-([A-Za-z]{3})\s+(\d{2}):(\d{2})Z$/);if(!m)return null;const month=['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec'].indexOf(m[2].toLowerCase());if(month<0||Number(m[1])>31||Number(m[3])>23||Number(m[4])>59)return null;let year=reference.getUTCFullYear();let date=new Date(Date.UTC(year,month,Number(m[1]),Number(m[3]),Number(m[4])));if(date.getTime()>reference.getTime()+86400000)date=new Date(Date.UTC(--year,month,Number(m[1]),Number(m[3]),Number(m[4])));if(date.getUTCMonth()!==month||date.getUTCDate()!==Number(m[1]))return null;return date.toISOString();}
|
||||
export function parseRadio(html){const t=plain(html);return {connected:/Connected to .*?(?:TNC|Modem)|Comms State Connected/i.test(t),state:t.match(/TNC State\s+(.*?)(?=Mode\b|Channel\b|Traffic\b|$)/)?.[1]?.trim()||'Free',busy:t.includes('Channel State Busy'),mode:t.match(/Mode (\S+)/)?.[1]||'',snr:t.match(/S\/N ([\d,.-]+)/)?.[1]||'—',sent:Number(t.match(/Traffic Sent (\d+)/)?.[1]||0),received:Number(t.match(/RXed (\d+)/)?.[1]||0),frequency:t.match(/\b(\d+\.\d+)\s+(?:USB|LSB|FM|DIG|DATA)\b/)?.[1]||'—',scanning:/\b\d+\.\d+\s+(?:USB|LSB|FM|DIG|DATA)\s+S\b/.test(t)};}
|
||||
@@ -0,0 +1,44 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import vm from 'node:vm';
|
||||
import {readFileSync} from 'node:fs';
|
||||
import {outgoingForm} from './mail-upload.mjs';
|
||||
import {parseMessage} from './bpq.mjs';
|
||||
|
||||
const source=readFileSync(new URL('./public/app.js',import.meta.url),'utf8');
|
||||
const bulletin={id:10,type:'B',from:'N1AUTHOR',to:'NEWS',via:'WW',subject:'Radio news',text:'First line\nSecond line'};
|
||||
function client(message){
|
||||
const elements=new Map(),field=()=>({value:'',focus(){}}),form={elements:{to:field(),type:field(),subject:field(),text:field()},reset(){for(const input of Object.values(this.elements))input.value='';this.elements.type.value='P';}};
|
||||
const $=selector=>{if(selector==='#compose-form')return form;if(!elements.has(selector))elements.set(selector,{innerHTML:'',textContent:'',showModal(){this.open=true;}});return elements.get(selector);};
|
||||
const context=vm.createContext({$,loadGeneration:0,selected:null,renderMessages(){},esc:v=>String(v??''),readableBody:v=>v,mailTimeMeta:()=>'',markMessageRead:async()=>{},toast(){},api:async()=>structuredClone(message)});
|
||||
for(const name of ['replyDraft','readMessage','openCompose'])vm.runInContext(source.split('\n').find(line=>line.startsWith('function '+name+'(')||line.startsWith('async function '+name+'(')),context);
|
||||
return {context,$,form};
|
||||
}
|
||||
test('Comment keeps bulletin type, category and distribution; Reply privately targets the author',async()=>{
|
||||
const view=client(bulletin);await view.context.readMessage(10);
|
||||
assert.match(view.$('#reader').innerHTML,/id="comment"/);assert.match(view.$('#reader').innerHTML,/id="reply"/);
|
||||
view.$('#comment').onclick();assert.equal(view.form.elements.type.value,'B');assert.equal(view.form.elements.to.value,'NEWS@WW');assert.equal(view.form.elements.subject.value,'Re: Radio news');assert.match(view.form.elements.text.value,/> First line\n> Second line/);
|
||||
assert.equal(view.$('#compose').open,true);
|
||||
view.$('#reply').onclick();assert.equal(view.form.elements.type.value,'P');assert.equal(view.form.elements.to.value,'N1AUTHOR');
|
||||
for(const kind of [false,true]){
|
||||
const draft=view.context.replyDraft(bulletin,kind),native=outgoingForm(draft);
|
||||
assert.equal(native.get('Type'),kind?'B':'P');assert.equal(native.get('To'),kind?'NEWS@WW':'N1AUTHOR');assert.equal(native.get('BID'),'');
|
||||
}
|
||||
});
|
||||
test('personal messages only offer Reply, and replying explicitly clears a previously selected bulletin type',async()=>{
|
||||
const view=client({...bulletin,type:'P',to:'N0LOCAL'});await view.context.readMessage(10);
|
||||
assert.doesNotMatch(view.$('#reader').innerHTML,/id="comment"/);
|
||||
view.form.elements.type.value='B';view.$('#reply').onclick();assert.equal(view.form.elements.type.value,'P');assert.equal(view.form.elements.to.value,'N1AUTHOR');
|
||||
});
|
||||
test('comments preserve embedded routes, do not invent a distribution, and avoid duplicate Re prefixes',()=>{
|
||||
const {context}=client(bulletin);
|
||||
assert.equal(context.replyDraft({...bulletin,to:'NEWS @ EU',via:'EU'},true).to,'NEWS@EU');
|
||||
assert.equal(context.replyDraft({...bulletin,via:''},true).to,'NEWS');
|
||||
assert.equal(context.replyDraft({...bulletin,subject:'Re: Radio news'},true).subject,'Re: Radio news');
|
||||
assert.equal(context.replyDraft({...bulletin,subject:'x'.repeat(80)},true).subject.length,80);
|
||||
assert.equal(context.replyDraft(bulletin).to,'N1AUTHOR');
|
||||
});
|
||||
test('native bulletin header preserves the distribution for reply drafts',()=>{
|
||||
const message=parseMessage('<textarea>From: N1AUTHOR\nTo: NEWS\nVia: EU\nTitle: Radio news\nType/Status: BN\n\nHello</textarea>');
|
||||
assert.equal(message.type,'B');assert.equal(message.via,'EU');const {context}=client(message);assert.equal(context.replyDraft(message,true).to,'NEWS@EU');
|
||||
});
|
||||
+18
-1
@@ -2,6 +2,22 @@ import {readFile} from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import os from 'node:os';
|
||||
import {fileURLToPath} from 'node:url';
|
||||
import {timingSafeEqual} from 'node:crypto';
|
||||
|
||||
export function validateSysopUsers(value,users){
|
||||
if(value===undefined)return undefined;
|
||||
if(!Array.isArray(value)||value.some(name=>typeof name!=='string'||!name.trim()))throw new Error('sysopUsers deve essere una lista di nomi utente SYSOP');
|
||||
const known=new Set(users.map(u=>u.user.toLowerCase()));
|
||||
const names=value.map(name=>name.trim());
|
||||
if(names.some(name=>!known.has(name.toLowerCase())))throw new Error('sysopUsers contiene un utente SYSOP non rilevato in BPQ32.cfg');
|
||||
return names.filter((name,index)=>names.findIndex(other=>other.toLowerCase()===name.toLowerCase())===index);
|
||||
}
|
||||
export function authenticateSysop(users,user,password,allowedUsers){
|
||||
const equal=(a,b)=>{const aa=Buffer.from(a),bb=Buffer.from(b);return aa.length===bb.length&&timingSafeEqual(aa,bb);};
|
||||
const found=users.find(u=>equal(u.user.toLowerCase(),user.toLowerCase())&&equal(u.password,password));
|
||||
if(!found||allowedUsers!==undefined&&!allowedUsers.some(name=>name.toLowerCase()===found.user.toLowerCase()))return null;
|
||||
return {call:found.call,name:found.user};
|
||||
}
|
||||
|
||||
export function parseConfig(text){
|
||||
let inText=false,inComment=false;const lines=[];
|
||||
@@ -25,13 +41,14 @@ export async function loadConfig(){
|
||||
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');
|
||||
const sysopUsers=validateSysopUsers(saved.sysopUsers,detected.users);
|
||||
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.sysopUser&&!detected.users.some(u=>u.user===saved.sysopUser))throw new Error('Utente sysop configurato non rilevato: rieseguire Install.ps1');
|
||||
const radio=detected.radioPorts.find(p=>p.id===Number(saved.radioPort))||detected.radioPorts[0]||null;
|
||||
const httpPort=Number(saved.httpPort||detected.httpPort);if(!validPort(httpPort))throw new Error('HTTPPORT BPQ non valida o assente: eseguire Install.ps1');
|
||||
const port=Number(process.env.BPQ_CONSOLE_PORT||saved.port||8090);if(!validPort(port,1024)||port===httpPort)throw new Error('Porta pannello non valida o in conflitto con HTTPPORT BPQ');
|
||||
const features={terminal:!!detected.telnetPort,bbs:detected.apps.some(a=>a.command==='BBS'),chat:detected.apps.some(a=>a.command==='CHAT')&&!!detected.telnetPort,monitor:!!detected.monitorPort,winlink:detected.winlink&&detected.apps.some(a=>a.command==='BBS'),vara:!!radio&&/^VARA/i.test(radio.driver),radio:!!radio};
|
||||
return {...detected,...saved,root,httpPort,radio,features,port,sysop:detected.users.find(u=>u.user===saved.sysopUser)||detected.users[0]};
|
||||
return {...detected,...saved,...(sysopUsers===undefined?{}:{sysopUsers}),root,httpPort,radio,features,port,sysop:detected.users.find(u=>u.user===saved.sysopUser)||detected.users[0]};
|
||||
}
|
||||
export const validPort=(n,min=1)=>Number.isInteger(n)&&n>=min&&n<=65535;
|
||||
export function publicConfig(c){return {call:c.sysop.call,nodeCall:c.nodeCall,alias:c.alias,locator:c.locator,apps:c.apps,radio:c.radio,ports:c.ports,features:c.features,forwardPeer:c.forwardPeer||'',cmsPeer:c.cmsPeer||'RMS'};}
|
||||
|
||||
@@ -23,6 +23,13 @@ test('explicit language overrides automatic detection and is saved per browser',
|
||||
test('UI translations handle counters, statuses, decorative icons and dynamic values',()=>{
|
||||
const {api}=client(['en']);
|
||||
assert.equal(api.t('↻ Sincronizza ora'),'↻ Sync now');
|
||||
assert.equal(api.t('▤ Commenta'),'▤ Comment');
|
||||
assert.equal(api.t('▦ Panoramica'),'▦ Overview');
|
||||
assert.equal(api.t('⌖ APRS'),'⌖ APRS');
|
||||
assert.equal(api.t('≋ Monitor'),'≋ Monitor');
|
||||
assert.equal(api.t('◷ Diario'),'◷ Logbook');
|
||||
assert.equal(api.t('▸_ Terminale'),'▸_ Terminal');
|
||||
assert.equal(api.t('📎 Allegati'),'📎 Attachments');
|
||||
assert.equal(api.t('Salva e metti in coda →'),'Save and queue →');
|
||||
assert.equal(api.t('12 bollettini · 3 personali'),'12 bulletins · 3 personal');
|
||||
assert.equal(api.t('● Connesso · N0TEST'),'● Connected · N0TEST');
|
||||
@@ -43,3 +50,25 @@ test('English preserves empty HTML text nodes and whitespace instead of insertin
|
||||
assert.equal(api.t(null),'');assert.equal(api.t(undefined),'');
|
||||
assert.equal(api.t(' Seleziona un messaggio '),' Select a message ');
|
||||
});
|
||||
|
||||
test('live APRS, radio controls, map counters and attachment statuses translate when built dynamically',()=>{
|
||||
const {api}=client(['en-US']);
|
||||
const labels=[
|
||||
['● APRS in tempo reale','● Live APRS'],
|
||||
['Attività','Activity'],['Configurazione','Configuration'],['Stazioni ricevute','Heard stations'],
|
||||
['Centra stazioni','Fit stations'],['Pausa vista','Pause display'],['Riprendi vista','Resume display'],
|
||||
['Tipo / pacchetto','Type / packet'],['Da → A','From → To'],['Oggetto APRS','APRS object'],
|
||||
['86 sulla mappa · 2 senza posizione','86 on map · 2 without position'],
|
||||
['2000 pacchetti nel registro','2000 packets in the log'],
|
||||
['Posizioni dai locator · UTC+02:00','Positions from locators · UTC+02:00'],
|
||||
['Dal 2026-10-04 · UTC+02:00','Since 2026-10-04 · UTC+02:00'],
|
||||
['● Frequenza fissa','● Fixed frequency'],['+ Frequenza','+ Frequency'],['PORTE RADIO','RADIO PORTS'],['Salva','Save'],
|
||||
['Frequenza APRS Port 3','APRS frequency port 3'],
|
||||
['Ricostruito da 3 parti · CRC verificati','Rebuilt from 3 parts · CRCs verified'],
|
||||
['3 parti ricostruite · CRC verificati','3 reconstructed parts · CRCs verified'],
|
||||
['Ricevute 2/3 parti. Mancano: 3.','Received 2/3 parts. Missing: 3.'],
|
||||
['Parte 1/3. Nessun blocco 7plus riconoscibile nel messaggio.','Part 1/3. No recognisable 7plus block in the message.'],
|
||||
];
|
||||
for(const [it,en]of labels){assert.equal(api.t(it),en,it);api.setLanguage('it');assert.equal(api.t(it),it);api.setLanguage('en');}
|
||||
assert.equal(api.t('image.jpg · 3 parti ricostruite · CRC verificati'),'image.jpg · 3 reconstructed parts · CRCs verified');
|
||||
});
|
||||
+3
-2
@@ -3,7 +3,7 @@ import http from 'node:http';
|
||||
import path from 'node:path';
|
||||
import os from 'node:os';
|
||||
import {fileURLToPath} from 'node:url';
|
||||
import {parseConfig,validPort} from './config.mjs';
|
||||
import {parseConfig,validPort,validateSysopUsers} from './config.mjs';
|
||||
import {parseForwarding} from './forwarding.mjs';
|
||||
import {modemFamily} from './winlink-gateways.mjs';
|
||||
|
||||
@@ -29,6 +29,7 @@ export async function prepareInstall(options={},dependencies={}){
|
||||
if(chosen!=null&&!radio)throw new Error('Porta radio selezionata non rilevata: specificare -RadioPort');
|
||||
const sysopUser=options.sysopUser??saved.sysopUser??detected.users[0].user;
|
||||
if(!detected.users.some(u=>u.user===sysopUser))throw new Error('Utente sysop non rilevato: specificare -SysopUser');
|
||||
const sysopUsers=validateSysopUsers(saved.sysopUsers,detected.users);
|
||||
let profiles=[];try{profiles=parseForwarding(await readFile(path.join(root,'BPQMailChat','BPQMail.cfg'),'utf8'),detected.ports);}catch(e){if(e.code!=='ENOENT')throw e;}
|
||||
const peers=profiles.map(p=>p.call),forwardPeer=String(options.forwardPeer??saved.forwardPeer??'').toUpperCase(),cmsPeer=String(options.cmsPeer??saved.cmsPeer??'RMS').toUpperCase();
|
||||
if(forwardPeer&&!peers.includes(forwardPeer))throw new Error('Profilo forwarding selezionato non rilevato');
|
||||
@@ -39,7 +40,7 @@ export async function prepareInstall(options={},dependencies={}){
|
||||
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 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)}};
|
||||
const config={...saved,...(sysopUsers===undefined?{}:{sysopUsers}),...(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.');
|
||||
|
||||
@@ -86,3 +86,13 @@ test('PowerShell startup confirms readiness, handles duplicate starts, restart a
|
||||
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');
|
||||
});
|
||||
|
||||
test('installer preserves the sysop allow-list for the same station, validates it and clears it for a different station',async t=>{
|
||||
const f=await fixture(t),saved={bpqRoot:f.root,sysopUser:'admin',sysopUsers:['OPERATOR']};
|
||||
await fs.writeFile(f.options.configPath,JSON.stringify(saved));
|
||||
const plan=await prepareInstall(f.options,{probe});assert.deepEqual(plan.config.sysopUsers,['OPERATOR']);await saveInstall(plan);
|
||||
assert.equal((await saveInstall(await prepareInstall(f.options,{probe}))).changed,false);
|
||||
await fs.writeFile(f.options.configPath,JSON.stringify({...saved,sysopUsers:['missing']}));await assert.rejects(prepareInstall(f.options,{probe}),/sysopUsers/);
|
||||
const other=path.join(f.dir,'other-station');await fs.mkdir(other);await fs.writeFile(path.join(other,'BPQ32.cfg'),cfg('ARDOP','N8OTHER'));
|
||||
assert.equal((await prepareInstall({...f.options,bpqRoot:other},{probe})).config.sysopUsers,undefined);
|
||||
});
|
||||
+5
-4
@@ -23,7 +23,8 @@ function mailTimezone(){const minutes=-new Date().getTimezoneOffset();return 'UT
|
||||
function mailTimeMeta(m){const zone=mailTimezone();const stamp=kind=>{const value=kind==='sent'?m.createdAt:m.receivedAt;return value?new Date(value).toLocaleString(BPQI18n.locale(),{day:'2-digit',month:'2-digit',year:'numeric',hour:'2-digit',minute:'2-digit'}):null;};return [stamp('sent')?'Inviato <b>'+esc(stamp('sent'))+'</b>':'',stamp('received')?'Ricevuto <b>'+esc(stamp('received'))+'</b>':'','Timezone: '+esc(zone)].filter(Boolean).map(x=>'<span>'+x+'</span>').join('');}
|
||||
function mailRow(m,selection,attribute,options={}){const unread=!m.read&&m.status==='N',current=selection===m.id;return `<button class="message-item mail-row ${current?'selected':''} ${unread?'unread':''}" ${attribute}="${m.id}" aria-pressed="${current}" title="${esc(m.subject)}"><span class="mail-indicator" aria-label="${unread?'Non letto':'Letto'}">${unread?'●':'○'}</span><span class="mail-from" title="${esc(options.from||m.from)}">${esc(options.from||m.from)}</span><span class="mail-subject">${esc(m.subject||'(Senza oggetto)')}${m.attachmentCount?'<span class="mail-paperclip" aria-label="Allegati" title="'+m.attachmentCount+' '+BPQI18n.t('Allegati')+'">📎 '+m.attachmentCount+'</span>':''}</span><span class="mail-category">${esc(options.category||m.to)}</span><time class="mail-date" datetime="${esc(m.receivedAt||m.createdAt||'')}" title="${esc(mailDate(m,'sent'))}">${esc(mailDate(m,options.dateKind))}</time><span class="mail-size">${size(m.size)}</span><span class="mail-status">${esc(options.status||m.status)}</span></button>`;}
|
||||
function renderMessages(){const q=$('#search').value.toLowerCase(),cat=$('#category').value;const list=allMessages.filter(m=>(filter==='all'||m.type===filter||filter==='sent'&&m.from.replace(/-\d+$/,'')===station.call.replace(/-\d+$/,''))&&(!cat||m.to===cat)&&(!q||`${m.subject} ${m.from} ${m.to} ${m.id}`.toLowerCase().includes(q)));$('#list-count').textContent=list.length+' messaggi';$('#message-list').innerHTML=list.map(m=>mailRow(m,selected,'data-id',{category:categoryLabel(m),status:m.status==='F'?'Inoltrato':m.status==='N'?(m.read?'Letto':'Nuovo'):m.status==='Y'?'Letto':m.status==='H'?'Trattenuto':m.status})).join('')||'<p class="empty">Nessun messaggio corrisponde ai filtri.</p>';$$('#message-list [data-id]').forEach(b=>b.onclick=()=>readMessage(Number(b.dataset.id)));}
|
||||
async function readMessage(id){const generation=++loadGeneration;selected=id;renderMessages();$('#reader').innerHTML='<div class="reader-empty"><h2>Caricamento messaggio…</h2></div>';try{const m=await api('/messages/'+id);if(generation!==loadGeneration)return;$('#reader').innerHTML=`<div class="reader-header"><span class="tag">${m.type==='B'?'BOLLETTINO':'MESSAGGIO PERSONALE'} · #${id}</span><h2>${esc(m.subject)}</h2><div class="reader-meta"><span>Da <b>${esc(m.from)}</b></span><span>A <b>${esc(m.to)}</b></span>${mailTimeMeta(m)}</div></div><div class="reader-body">${readableBody(m.text)}</div><footer class="reader-footer"><span>BID ${esc(m.bid||'—')}</span><button class="secondary" id="reply">↩ Rispondi</button></footer>`;markMessageRead(id).catch(error=>toast(error.message));$('#reply').onclick=()=>openCompose({to:m.from,subject:(/^Re:/i.test(m.subject)?m.subject:'Re: '+m.subject).slice(0,80),text:'\n\n--- '+m.from+' ---\n'+m.text.split('\n').map(l=>'> '+l).join('\n')});}catch(err){$('#reader').innerHTML=`<div class="reader-empty"><h2>Messaggio non disponibile</h2><p>${esc(err.message)}</p></div>`}}
|
||||
function replyDraft(message,comment=false){const bulletin=comment&&message.type==='B',destination=String((bulletin?message.to:message.from)||'').trim().replace(/\s*@\s*/g,'@'),via=String(message.via||'').trim();return {to:bulletin&&via&&!destination.includes('@')?destination+'@'+via:destination,type:bulletin?'B':'P',subject:(/^Re:/i.test(message.subject)?message.subject:'Re: '+message.subject).slice(0,80),text:'\n\n--- '+message.from+' ---\n'+message.text.split('\n').map(line=>'> '+line).join('\n')};}
|
||||
async function readMessage(id){const generation=++loadGeneration;selected=id;renderMessages();$('#reader').innerHTML='<div class="reader-empty"><h2>Caricamento messaggio…</h2></div>';try{const m=await api('/messages/'+id);if(generation!==loadGeneration)return;$('#reader').innerHTML=`<div class="reader-header"><span class="tag">${m.type==='B'?'BOLLETTINO':'MESSAGGIO PERSONALE'} · #${id}</span><h2>${esc(m.subject)}</h2><div class="reader-meta"><span>Da <b>${esc(m.from)}</b></span><span>A <b>${esc(m.to)}</b></span>${mailTimeMeta(m)}</div></div><div class="reader-body">${readableBody(m.text)}</div><footer class="reader-footer"><span>BID ${esc(m.bid||'—')}</span><div class="reader-reply-actions">${m.type==='B'?'<button class="secondary" id="comment" title="Pubblica un commento come bollettino">▤ Commenta</button>':''}<button class="secondary" id="reply" title="Rispondi all’autore con un messaggio personale">↩ Rispondi</button></div></footer>`;markMessageRead(id).catch(error=>toast(error.message));$('#reply').onclick=()=>openCompose(replyDraft(m));if(m.type==='B')$('#comment').onclick=()=>openCompose(replyDraft(m,true));}catch(err){$('#reader').innerHTML=`<div class="reader-empty"><h2>Messaggio non disponibile</h2><p>${esc(err.message)}</p></div>`}}
|
||||
$$('[data-filter]').forEach(b=>b.onclick=()=>{filter=b.dataset.filter;$$('[data-filter]').forEach(x=>x.classList.toggle('active',x===b));renderMessages()});$('#search').oninput=renderMessages;$('#category').onchange=renderMessages;
|
||||
function openCompose(data={}){const f=$('#compose-form');f.reset();for(const [key,value]of Object.entries(data))f.elements[key].value=value;$('#compose-error').textContent='';$('#compose').showModal();f.elements.to.focus()}
|
||||
$$('.compose-button').forEach(b=>b.onclick=()=>openCompose());$$('.close-compose').forEach(b=>b.onclick=()=>{const f=$('#compose-form');if((f.elements.text.value||f.elements.subject.value||window.bpqComposeAttachments?.count())&&!bpqConfirm('Chiudere e scartare questa bozza?'))return;$('#compose').close()});
|
||||
@@ -37,10 +38,10 @@ function applyStation(user){
|
||||
document.title='BPQ Console · '+station.nodeCall;
|
||||
$('.side-station').textContent=[station.nodeCall,station.alias,station.locator].filter(Boolean).join(' · ');
|
||||
$('.profile .avatar').textContent=station.call.slice(0,2);
|
||||
$('.profile > div:nth-child(2)').textContent=user.name+' · '+station.call;
|
||||
$('.profile > div:nth-child(2)').textContent=user.name+' · '+user.call;
|
||||
$('.mission-heading h1').textContent=station.nodeCall+' / '+station.alias;
|
||||
$('.mission-location').textContent=station.locator||'BPQ';
|
||||
$('.modem-brand').textContent=station.radio?.name||'Nessuna porta modem';
|
||||
$('.modem-brand').textContent=station.radio?.name||BPQI18n.t('Nessuna porta modem');
|
||||
$('#home .page-footer').firstChild.textContent='BPQ Console · '+station.nodeCall+' ';
|
||||
$('#compose .eyebrow').textContent=station.call;
|
||||
$('.compose-help').textContent='Il messaggio sarà salvato nella BBS. L’inoltro segue i profili BPQ.';
|
||||
@@ -60,6 +61,6 @@ function applyStation(user){
|
||||
if(!station.features[page]&&['bbs','chat','winlink','monitor'].includes(page))navigate('home');
|
||||
}
|
||||
|
||||
document.addEventListener('bpq-languagechange',()=>{if(csrf){renderMessages();if(typeof wlRender==='function')wlRender();}});
|
||||
document.addEventListener('bpq-languagechange',()=>{if(csrf){if(!station.radio)$('.modem-brand').textContent=BPQI18n.t('Nessuna porta modem');renderMessages();if(typeof wlRender==='function')wlRender();}});
|
||||
|
||||
async function markMessageRead(id){const state=await api('/messages/'+id+'/read',{method:'POST',body:'{}'});for(const item of allMessages)if(item.id===id)Object.assign(item,state);if(typeof wlData!=='undefined'&&wlData)for(const item of wlData.messages)if(item.id===id)Object.assign(item,state);renderMessages();if(typeof wlRender==='function')wlRender();}
|
||||
@@ -6,7 +6,7 @@
|
||||
const snapshots=new WeakMap();
|
||||
function markup(selector,html){const el=$(selector);if(snapshots.get(el)===html)return;snapshots.set(el,html);el.innerHTML=html;}
|
||||
const time=t=>t?new Date(t).toLocaleString(BPQI18n.locale(),{day:'2-digit',month:'2-digit',hour:'2-digit',minute:'2-digit',second:'2-digit'}):'—';
|
||||
const type=t=>({position:'Posizione',message:'Messaggio',status:'Stato',object:'Oggetto',weather:'Meteo',telemetry:'Telemetria','third-party':'Messaggio inoltrato',query:'Richiesta'}[t]||t);
|
||||
const type=t=>({position:'Posizione',message:'Messaggio',status:'Stato',object:'Oggetto APRS',weather:'Meteo',telemetry:'Telemetria','third-party':'Messaggio inoltrato',query:'Richiesta'}[t]||t);
|
||||
const source=()=>$('#aprs-source').value,query=()=>$('#aprs-search').value.trim().toUpperCase();
|
||||
const stations=()=>data?.stations.filter(s=>(!source()||s.transport===source()||source()==='Radio'&&s.heardRadio)&&(!query()||(s.call+' '+s.status+' '+s.lastBody).toUpperCase().includes(query())))||[];
|
||||
function setView(next){view=next;form.hidden=next!=='config';pane.hidden=next!=='activity';$('#aprs-save').hidden=next!=='config';tabs.querySelectorAll('button').forEach(b=>b.setAttribute('aria-selected',String(b.dataset.aprsView===next)));if(next==='activity'&&page==='aprs'){start();requestAnimationFrame(()=>map?.invalidateSize({pan:false}));}}
|
||||
|
||||
@@ -2,6 +2,8 @@ let attachmentGeneration=0,attachmentPdf=null;
|
||||
const attachmentDialog=document.createElement('dialog');attachmentDialog.className='attachment-dialog';attachmentDialog.innerHTML='<div class="dialog-heading"><h2 id="attachment-title">Allegato</h2><button id="attachment-close" class="icon-button" aria-label="Chiudi anteprima">×</button></div><div id="attachment-preview"></div><footer><a id="attachment-download" class="primary" download>Scarica file ↓</a></footer>';document.body.append(attachmentDialog);$('#attachment-close').onclick=()=>attachmentDialog.close();attachmentDialog.addEventListener('close',()=>{attachmentGeneration++;attachmentPdf?.destroy().catch(()=>{});attachmentPdf=null;$('#attachment-preview').replaceChildren();});
|
||||
async function renderPdf(url,generation){const pdfjs=await import('/vendor/pdfjs/pdf.min.mjs');pdfjs.GlobalWorkerOptions.workerSrc='/vendor/pdfjs/pdf.worker.min.mjs';const documentPdf=await pdfjs.getDocument({url,withCredentials:true,isEvalSupported:false,enableXfa:false,disableFontFace:true,useSystemFonts:true,standardFontDataUrl:'/vendor/pdfjs/standard_fonts/',cMapUrl:'/vendor/pdfjs/cmaps/',cMapPacked:true}).promise;if(generation!==attachmentGeneration){await documentPdf.destroy();return;}attachmentPdf=documentPdf;const preview=$('#attachment-preview');preview.innerHTML='<div class="pdf-controls"><button id="pdf-previous" class="secondary">←</button><span id="pdf-page"></span><button id="pdf-next" class="secondary">→</button></div><canvas id="pdf-canvas" aria-label="Anteprima pagina PDF"></canvas>';let page=1,busy=false;async function draw(){if(busy||generation!==attachmentGeneration)return;busy=true;try{const p=await documentPdf.getPage(page);const v=p.getViewport({scale:1});const scale=Math.min(2,Math.max(1,(preview.clientWidth-30)/v.width));const viewport=p.getViewport({scale});const canvas=$('#pdf-canvas');if(!canvas||generation!==attachmentGeneration)return;canvas.width=viewport.width;canvas.height=viewport.height;await p.render({canvasContext:canvas.getContext('2d'),viewport}).promise;$('#pdf-page').textContent=page+' / '+documentPdf.numPages;$('#pdf-previous').disabled=page===1;$('#pdf-next').disabled=page===documentPdf.numPages;}finally{busy=false}}$('#pdf-previous').onclick=()=>{if(page>1&&!busy){page--;draw()}};$('#pdf-next').onclick=()=>{if(page<documentPdf.numPages&&!busy){page++;draw()}};await draw();}
|
||||
async function openAttachment(id,file){const generation=++attachmentGeneration;$('#attachment-title').textContent=file.name;const url='/api/messages/'+id+'/attachments/'+file.index;$('#attachment-download').href=url;$('#attachment-preview').innerHTML='<p class="empty">Caricamento anteprima…</p>';attachmentDialog.showModal();if(file.mime.startsWith('image/')){const image=document.createElement('img');image.alt=file.name;image.src=url+'?preview=1';image.onerror=()=>$('#attachment-preview').innerHTML='<p class="empty">Anteprima non disponibile. Puoi scaricare il file.</p>';$('#attachment-preview').replaceChildren(image);}else if(file.mime==='application/pdf'){try{await renderPdf(url+'?preview=1',generation)}catch{if(generation===attachmentGeneration)$('#attachment-preview').innerHTML='<p class="empty">Anteprima PDF non disponibile. Puoi scaricare il file.</p>';}}else if(file.mime==='text/plain'){try{const data=await api('/messages/'+id+'/attachments/'+file.index+'?text=1');if(generation!==attachmentGeneration)return;const pre=document.createElement('pre');pre.textContent=data.text;$('#attachment-preview').replaceChildren(pre);if(data.truncated){const hint=document.createElement('p');hint.className='muted';hint.textContent='Anteprima limitata ai primi 128 KB. Il download contiene il file completo.';$('#attachment-preview').append(hint)}}catch(e){$('#attachment-preview').textContent=e.message}}else{$('#attachment-preview').innerHTML='<p class="empty">Anteprima non disponibile per questo formato. Puoi scaricare il file.</p>';}}
|
||||
async function showAttachments(id,reader){const section=document.createElement('section');section.className='message-attachments';section.innerHTML='<span class="muted">Controllo allegati…</span>';reader.querySelector('.reader-footer')?.before(section);try{const data=await api('/messages/'+id+'/attachments');if(!section.isConnected)return;if(!data.files.length&&!data.encoded){section.remove();return;}section.replaceChildren();reader.querySelector('.reader-attachment-count')?.remove();if(data.files.length){const count=document.createElement('span');count.className='reader-attachment-count';count.textContent='📎 '+data.files.length;count.title='Allegati';reader.querySelector('.reader-header .tag')?.after(count);}if(data.files.length){const heading=document.createElement('h3');heading.textContent='Allegati · '+data.files.length;section.append(heading);for(const file of data.files){const row=document.createElement('div');row.className='attachment-row';row.innerHTML=`<span class="attachment-icon">${file.mime.startsWith('image/')?'▧':file.mime==='application/pdf'?'PDF':'▤'}</span><div><b>${esc(file.name)}</b><small>${size(file.size)}${file.reconstructed?' · Ricostruito da '+file.parts+' parti · CRC verificati':''}</small></div><button class="secondary attachment-open">Anteprima</button><a class="secondary" href="/api/messages/${id}/attachments/${file.index}" download>Scarica ↓</a>`;row.querySelector('button').onclick=()=>openAttachment(id,file);if(file.mime==='application/octet-stream')row.querySelector('button').hidden=true;section.append(row);}}if(data.encoded?.state==='complete'){const imageFile=data.files.find(f=>f.reconstructed&&f.mime.startsWith('image/')),body=reader.querySelector('.reader-body');if(imageFile&&body){const original=document.createElement('details');original.className='sevenplus-original';const summary=document.createElement('summary');summary.textContent='Mostra messaggio originale e dati 7plus';original.append(summary,...body.childNodes);const preview=document.createElement('div');preview.className='sevenplus-inline';const img=document.createElement('img');img.src='/api/messages/'+id+'/attachments/'+imageFile.index+'?preview=1';img.alt=imageFile.name;img.loading='lazy';img.onclick=()=>openAttachment(id,imageFile);const caption=document.createElement('p');caption.textContent=imageFile.name+' · '+imageFile.parts+' parti ricostruite · CRC verificati';preview.append(img,caption);body.replaceChildren(preview,original);}}if(data.encoded){const box=document.createElement('div');box.className='encoded-attachment';box.innerHTML=`<b>7plus · ${esc(data.encoded.name)}</b><p>${data.encoded.state==='complete'?'Ricostruzione completa · '+data.encoded.total+'/'+data.encoded.total+' parti verificate. Anteprima e download disponibili negli allegati.':data.encoded.state==='incomplete'?'Ricevute '+data.encoded.availableParts.length+'/'+data.encoded.total+' parti. Mancano: '+data.encoded.missingParts.join(', ')+'.'+(data.encoded.damagedParts.length?' Parti danneggiate: '+data.encoded.damagedParts.join(', ')+'.':''):data.encoded.state==='damaged'?'Ricostruzione sospesa: dati incompleti o CRC non validi nelle parti '+data.encoded.damagedParts.join(', ')+'.':'Parte '+data.encoded.part+'/'+data.encoded.total+'. Nessun blocco 7plus riconoscibile nel messaggio.'}</p>${data.encoded.issues?.length?'<p>'+esc(data.encoded.issues.join(' · '))+'</p>':''}${data.encoded.messageIds?.length?'<div class="sevenplus-parts">'+data.encoded.messageIds.map(mid=>'<button class="text-button" data-seven-message="'+mid+'">#'+mid+'</button>').join('')+'</div>':''}<a class="text-button" href="/api/messages/${id}/source" download>Scarica testo originale della parte ↓</a>`;section.append(box);box.querySelectorAll('[data-seven-message]').forEach(b=>b.onclick=()=>{navigate('bbs');readMessage(Number(b.dataset.sevenMessage));});}}catch(e){section.innerHTML=`<span class="muted">${esc(e.message)}</span>`;}}
|
||||
async function showAttachments(id,reader){const section=document.createElement('section');section.className='message-attachments';section.innerHTML='<span class="muted">Controllo allegati…</span>';reader.querySelector('.reader-footer')?.before(section);try{const data=await api('/messages/'+id+'/attachments');if(!section.isConnected)return;if(!data.files.length&&!data.encoded){section.remove();return;}section.replaceChildren();reader.querySelector('.reader-attachment-count')?.remove();if(data.files.length){const count=document.createElement('span');count.className='reader-attachment-count';count.textContent='📎 '+data.files.length;count.title='Allegati';reader.querySelector('.reader-header .tag')?.after(count);}if(data.files.length){const heading=document.createElement('h3');heading.textContent='Allegati · '+data.files.length;section.append(heading);for(const file of data.files){const row=document.createElement('div');row.className='attachment-row';row.innerHTML=`<span class="attachment-icon">${file.mime.startsWith('image/')?'▧':file.mime==='application/pdf'?'PDF':'▤'}</span><div><b>${esc(file.name)}</b><small>${size(file.size)}${file.reconstructed?' · Ricostruito da '+file.parts+' parti · CRC verificati':''}</small></div><button class="secondary attachment-open">Anteprima</button><a class="secondary" href="/api/messages/${id}/attachments/${file.index}" download>Scarica ↓</a>`;row.querySelector('button').onclick=()=>openAttachment(id,file);if(file.mime==='application/octet-stream')row.querySelector('button').hidden=true;section.append(row);}}if(data.encoded?.state==='complete'){const imageFile=data.files.find(f=>f.reconstructed&&f.mime.startsWith('image/')),body=reader.querySelector('.reader-body');if(imageFile&&body){const original=document.createElement('details');original.className='sevenplus-original';const summary=document.createElement('summary');summary.textContent='Mostra messaggio originale e dati 7plus';original.append(summary,...body.childNodes);const preview=document.createElement('div');preview.className='sevenplus-inline';const img=document.createElement('img');img.src='/api/messages/'+id+'/attachments/'+imageFile.index+'?preview=1';img.alt=imageFile.name;img.loading='lazy';img.onclick=()=>openAttachment(id,imageFile);const caption=document.createElement('p');caption.dataset.fileName=imageFile.name;caption.dataset.parts=imageFile.parts;caption.textContent=imageFile.name+' · '+BPQI18n.t(imageFile.parts+' parti ricostruite · CRC verificati');preview.append(img,caption);body.replaceChildren(preview,original);}}if(data.encoded){const box=document.createElement('div');box.className='encoded-attachment';box.innerHTML=`<b>7plus · ${esc(data.encoded.name)}</b><p>${data.encoded.state==='complete'?'Ricostruzione completa · '+data.encoded.total+'/'+data.encoded.total+' parti verificate. Anteprima e download disponibili negli allegati.':data.encoded.state==='incomplete'?'Ricevute '+data.encoded.availableParts.length+'/'+data.encoded.total+' parti. Mancano: '+data.encoded.missingParts.join(', ')+'.'+(data.encoded.damagedParts.length?' Parti danneggiate: '+data.encoded.damagedParts.join(', ')+'.':''):data.encoded.state==='damaged'?'Ricostruzione sospesa: dati incompleti o CRC non validi nelle parti '+data.encoded.damagedParts.join(', ')+'.':'Parte '+data.encoded.part+'/'+data.encoded.total+'. Nessun blocco 7plus riconoscibile nel messaggio.'}</p>${data.encoded.issues?.length?'<p>'+esc(data.encoded.issues.join(' · '))+'</p>':''}${data.encoded.messageIds?.length?'<div class="sevenplus-parts">'+data.encoded.messageIds.map(mid=>'<button class="text-button" data-seven-message="'+mid+'">#'+mid+'</button>').join('')+'</div>':''}<a class="text-button" href="/api/messages/${id}/source" download>Scarica testo originale della parte ↓</a>`;section.append(box);box.querySelectorAll('[data-seven-message]').forEach(b=>b.onclick=()=>{navigate('bbs');readMessage(Number(b.dataset.sevenMessage));});}}catch(e){section.innerHTML=`<span class="muted">${esc(e.message)}</span>`;}}
|
||||
const attachmentRead=readMessage;readMessage=async function(id){await attachmentRead(id);if(selected===id&&$('#reader .reader-footer'))showAttachments(id,$('#reader'));};
|
||||
const attachmentWlRead=wlRead;wlRead=async function(id){await attachmentWlRead(id);if(wlSelected===id&&$('#wl-reader .reader-footer'))showAttachments(id,$('#wl-reader'));};
|
||||
|
||||
document.addEventListener('bpq-languagechange',()=>{$$('.sevenplus-inline p[data-parts]').forEach(caption=>{caption.textContent=caption.dataset.fileName+' · '+BPQI18n.t(caption.dataset.parts+' parti ricostruite · CRC verificati');});});
|
||||
@@ -115,3 +115,5 @@ html{scrollbar-gutter:stable}
|
||||
@media(max-width:700px){#shell .page:not(#home){padding:20px 16px}#shell .topbar{padding-inline:16px}#shell .page :is(.page-heading,.journal-heading,.forward-heading,.chat-heading,.monitor-heading,.terminal-heading){flex-wrap:wrap;gap:12px}#shell .page :is(.page-heading,.journal-heading,.forward-heading,.chat-heading,.monitor-heading,.terminal-heading) h1{font-size:23px}#shell .page :is(.journal-kpis,.forward-summary,.aprs-activity-kpis){gap:10px}#shell .page :is(.journal-kpis article,.forward-summary>div,.aprs-activity-kpis article){padding:14px}}
|
||||
@media(max-width:600px){#shell .sidebar{padding:16px}#shell .sidebar .brand{margin:0}#shell nav button{margin:0;min-height:38px;font-size:12px;padding:8px 10px}}
|
||||
@media(prefers-reduced-motion:reduce){.arrival-toast{animation:none}.chat-messages{scroll-behavior:auto}}
|
||||
|
||||
.reader-reply-actions{display:flex;align-items:center;gap:8px;flex-wrap:wrap}.reader-footer:has(.reader-reply-actions){gap:12px;flex-wrap:wrap}.reader-footer .reader-reply-actions button{white-space:nowrap}@media(max-width:600px){.reader-footer .reader-reply-actions{flex:1}.reader-footer .reader-reply-actions button{flex:1}}
|
||||
+79
-4
@@ -4,6 +4,9 @@
|
||||
const entries=`
|
||||
Dal|Since
|
||||
Dettagli del registro|Log details
|
||||
Commenta|Comment
|
||||
Pubblica un commento come bollettino|Post a comment as a bulletin
|
||||
Rispondi all’autore con un messaggio personale|Reply privately to the author
|
||||
Seleziona un messaggio|Select a message
|
||||
Mappa delle stazioni|Station map
|
||||
Seleziona un collegamento|Select a connection
|
||||
@@ -707,7 +710,63 @@ Configurazione APRS applicata|APRS configuration applied
|
||||
Configurato · lascia vuoto per mantenerlo|Configured · leave blank to keep it
|
||||
Non configurato|Not configured
|
||||
Stazione / APRS|Station / APRS`;
|
||||
const dictionary=new Map((entries+'\n'+uploadCopy+'\n'+sizeCopy+'\n'+deleteCopy+'\n'+portCopy+'\n'+aprsCopy).split(/\r?\n/).map(line=>line.split('|')).filter(([source,target])=>source?.trim()&&typeof target==='string'&&target.trim()));
|
||||
const liveCopy=`Attività|Activity
|
||||
Configurazione|Configuration
|
||||
Viste APRS|APRS views
|
||||
Origine APRS|APRS source
|
||||
Direzione APRS|APRS direction
|
||||
Cerca APRS|Search APRS
|
||||
Mappa stazioni APRS|APRS station map
|
||||
Pausa vista|Pause display
|
||||
Riprendi vista|Resume display
|
||||
Vista in pausa|Display paused
|
||||
APRS in tempo reale|Live APRS
|
||||
Stazioni ricevute|Heard stations
|
||||
Centra stazioni|Fit stations
|
||||
La tua stazione|Your station
|
||||
Ultime ricezioni|Recently heard
|
||||
Traffico APRS|APRS traffic
|
||||
Da → A|From → To
|
||||
Tipo / pacchetto|Type / packet
|
||||
Senza posizione|No position
|
||||
senza posizione|without position
|
||||
sulla mappa|on map
|
||||
Nessuna stazione ricevuta con questi filtri.|No stations match these filters.
|
||||
In attesa di pacchetti APRS ricevuti o inviati.|Waiting for received or transmitted APRS packets.
|
||||
Posizione|Position
|
||||
Oggetto APRS|APRS object
|
||||
Meteo|Weather
|
||||
Telemetria|Telemetry
|
||||
Messaggio inoltrato|Forwarded message
|
||||
Richiesta|Request
|
||||
pacchetti nel registro|packets in the log
|
||||
Ultimi 2000 pacchetti · TX radio = richieste registrate da BPQ.|Last 2000 packets · Radio TX = requests logged by BPQ.
|
||||
Log Internet non disponibile|Internet log unavailable
|
||||
Aggiornato|Updated
|
||||
Salva|Save
|
||||
BBS & messaggi|BBS & messages
|
||||
messaggi|messages
|
||||
messaggio ricevuto|message received
|
||||
messaggi ricevuti|messages received
|
||||
destinazioni|destinations
|
||||
stazioni|stations
|
||||
stazione locale|local station
|
||||
in ascolto|listening
|
||||
— messaggi|— messages
|
||||
— presenti|— online
|
||||
Scrivi un messaggio…|Write a message…
|
||||
BBS / STAZIONE|BBS / STATION
|
||||
Il messaggio sarà salvato nella BBS come STAZIONE. L’inoltro segue le rotte configurate in BPQ.|The message will be saved in the station BBS. BPQ handles forwarding using its configured routes.
|
||||
Chiamata radio verso il nodo remoto avviata|Radio call to the remote node started
|
||||
il nodo remoto si è collegato alla nostra BBS|the remote node connected to our BBS
|
||||
Ricevuto e salvato un nuovo bollettino|New bulletin received and saved
|
||||
Servizio|Service
|
||||
Connessione UTC|Connection UTC
|
||||
Messaggi TX|Messages TX
|
||||
Messaggi RX|Messages RX
|
||||
CRC verificati|CRCs verified
|
||||
Sync automatico gestito dalla console.|Automatic sync managed by the console.`;
|
||||
const dictionary=new Map((entries+'\n'+uploadCopy+'\n'+sizeCopy+'\n'+deleteCopy+'\n'+portCopy+'\n'+aprsCopy+'\n'+liveCopy).split(/\r?\n/).map(line=>line.split('|')).filter(([source,target])=>source?.trim()&&typeof target==='string'&&target.trim()));
|
||||
function resolveLanguage(preference=null,languages=[]){
|
||||
if(preference==='it'||preference==='en')return preference;
|
||||
// The first browser language is the user's preferred UI language; English is the fallback.
|
||||
@@ -732,8 +791,23 @@ Stazione / APRS|Station / APRS`;
|
||||
[/^Attiva · intervallo (.+)$/,m=>'Enabled · interval '+m[1]],
|
||||
[/^Porta (\d+)$/,m=>'Port '+m[1]],
|
||||
[/^Posizioni dai locator · orari (.+)$/,m=>'Positions from locators · times '+m[1]],
|
||||
[/^Posizioni dai locator · (.+)$/,m=>'Positions from locators · '+m[1]],
|
||||
[/^Log disponibili dal (.+) · massimo 30 giorni · (.+)$/,m=>'Logs available since '+m[1]+' · up to 30 days · '+m[2]],
|
||||
[/^(\d+) sulla mappa · (\d+) senza locator$/,m=>m[1]+' on map · '+m[2]+' without locator'],
|
||||
[/^(\d+) sulla mappa · (\d+) senza posizione$/,m=>m[1]+' on map · '+m[2]+' without position'],
|
||||
[/^(\d+) pacchetti nel registro$/,m=>m[1]+' packets in the log'],
|
||||
[/^Dal (.+)$/,m=>'Since '+m[1]],
|
||||
[/^Frequenza APRS Port (\d+)$/,m=>'APRS frequency port '+m[1]],
|
||||
[/^Frequenza FM: (.+)$/,m=>'FM frequency: '+m[1]],
|
||||
[/^(.+) · ultimo collegamento (.+)$/,m=>m[1]+' · last connection '+m[2]],
|
||||
[/^Sync automatico gestito dalla console\. (.+)$/,m=>'Automatic sync managed by the console. '+translate(m[1])],
|
||||
[/^Stessa coda e stesse regole del partner (\S+)\. Sync automatico gestito dalla console\. (.+)$/,m=>'Same queue and rules as partner '+m[1]+'. Automatic sync managed by the console. '+translate(m[2])],
|
||||
[/^(\d+) parti ricostruite$/,m=>m[1]+' reconstructed parts'],
|
||||
[/^Ricostruito da (\d+) parti$/,m=>'Rebuilt from '+m[1]+' parts'],
|
||||
[/^Ricostruzione completa · (\d+)\/(\d+) parti verificate\. Anteprima e download disponibili negli allegati\.$/,m=>'Reconstruction complete · '+m[1]+'/'+m[2]+' verified parts. Preview and download available in attachments.'],
|
||||
[/^Ricevute (\d+)\/(\d+) parti\. Mancano: ([\d, ]+)\.(?: Parti danneggiate: ([\d, ]+)\.)?$/,m=>'Received '+m[1]+'/'+m[2]+' parts. Missing: '+m[3]+'.'+(m[4]?' Damaged parts: '+m[4]+'.':'')],
|
||||
[/^Ricostruzione sospesa: dati incompleti o CRC non validi nelle parti ([\d, ]+)\.$/,m=>'Reconstruction suspended: incomplete data or invalid CRCs in parts '+m[1]+'.'],
|
||||
[/^Parte (\d+)\/(\d+)\. Nessun blocco 7plus riconoscibile nel messaggio\.$/,m=>'Part '+m[1]+'/'+m[2]+'. No recognisable 7plus block in the message.'],
|
||||
[/^(\d+) km dal nodo$/,m=>m[1]+' km from node'],
|
||||
[/^Locator salvato per (\S+)$/,m=>'Locator saved for '+m[1]],
|
||||
[/^(\d+) canali? · (\d+) gateway$/,m=>m[1]+' '+(m[1]==='1'?'channel':'channels')+' · '+m[2]+' gateways'],
|
||||
@@ -752,8 +826,9 @@ Stazione / APRS|Station / APRS`;
|
||||
}
|
||||
function t(value){
|
||||
const text=String(value??'');if(language!=='en')return text;
|
||||
const whole=text.match(/^(\s*)(.*?)(\s*)$/s);if(whole&&dictionary.has(whole[2]))return whole[1]+dictionary.get(whole[2])+whole[3];
|
||||
// Preserve indentation and decorative icons, which often live in the same text node.
|
||||
const match=text.match(/^(\s*[●◇◎+↻↩⇄◉↓↑]*\s*)(.*?)(\s*[→↗↓↵]*\s*)$/s);
|
||||
const match=text.match(/^(\s*(?:(?:▸_|[\p{S}\uFE0E\uFE0F])\s*)*)(.*?)(\s*(?:[\p{S}\uFE0E\uFE0F]\s*)*)$/su);
|
||||
return match?match[1]+translate(match[2])+match[3]:translate(text);
|
||||
}
|
||||
const api={t,resolveLanguage,get language(){return language},get preference(){return preference},locale:()=>language==='it'?'it-IT':'en-GB'};
|
||||
@@ -764,8 +839,8 @@ Stazione / APRS|Station / APRS`;
|
||||
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';
|
||||
function excluded(el){return !el||!!el.closest(protectedContent);}
|
||||
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,.aprs-packet-preview,.aprs-received-station p,.aprs-map-popup p,.aprs-map-popup b,.aprs-map-popup small';
|
||||
function excluded(el){if(!el)return true;if(el.matches('.routing-trace>summary,.sevenplus-original>summary'))return false;return !!el.closest(protectedContent);}
|
||||
function textNode(node){
|
||||
if(excluded(node.parentElement))return;
|
||||
let entry=originals.get(node);
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
<!doctype html>
|
||||
<html lang="it"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="theme-color" content="#101916"><title>BPQ Console</title><link rel="stylesheet" href="/i18n.css"><script src="/ui-config.js"></script><script src="/i18n.js?v=20261018-empty-text-fix"></script><link rel="stylesheet" href="/style.css"><link rel="stylesheet" href="/dark.css"><link rel="stylesheet" href="/mission.css"><link rel="stylesheet" href="/busy.css"><script defer src="/busy.js"></script><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="/compose-attachments.css"><script defer src="/compose-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?v=20261017-hourly-2"></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"><link rel="stylesheet" href="/radio-ports.css"><script defer src="/radio-ports.js"></script><link rel="stylesheet" href="/aprs.css"><script defer src="/aprs.js"></script><link rel="stylesheet" href="/vendor/leaflet/leaflet.css"><script defer src="/vendor/leaflet/leaflet.js"></script><link rel="stylesheet" href="/aprs-activity.css?v=20261017-3"><script defer src="/aprs-activity.js?v=20261017-3"></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?v=20261019-label-audit"></script><link rel="stylesheet" href="/style.css"><link rel="stylesheet" href="/dark.css"><link rel="stylesheet" href="/mission.css"><link rel="stylesheet" href="/busy.css"><script defer src="/busy.js"></script><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="/compose-attachments.css"><script defer src="/compose-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?v=20261017-hourly-2"></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"><link rel="stylesheet" href="/radio-ports.css"><script defer src="/radio-ports.js"></script><link rel="stylesheet" href="/aprs.css"><script defer src="/aprs.js"></script><link rel="stylesheet" href="/vendor/leaflet/leaflet.css"><script defer src="/vendor/leaflet/leaflet.js"></script><link rel="stylesheet" href="/aprs-activity.css?v=20261017-3"><script defer src="/aprs-activity.js?v=20261017-3"></script><link rel="stylesheet" href="/sync-progress.css"><script type="module" src="/sync-progress.js"></script></head>
|
||||
<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>
|
||||
<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>
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
function renderSelected(){const p=port();if(!p)return;const originalRadio=station.radio,originalControl=window.bpqRadioControl;station.radio={id:p.id,name:p.name,driver:p.driver};window.bpqRadioControl={txSuspended:data.global.txSuspended||p.control.txSuspended||!p.control.listening};
|
||||
try{legacyRender({current:p.current,history:p.history});$('#radio-status').textContent=!p.control.listening?'PORTA FERMA':window.bpqRadioControl.txSuspended?'TX SOSPESO':!p.current.available?'OFFLINE':p.current.ptt?'TX':p.current.active?'LINK ATTIVO':'IN ASCOLTO';$('#session-detail').textContent=p.name;$('#modem-traffic').textContent=p.current.sent!=null?'TX '+size(p.current.sent)+' / RX '+size(p.current.received||0):'TX '+rate(p.current.txFrames)+' / RX '+rate(p.current.rxFrames)+' frame';$('#bps-value').textContent=p.current.txBps==null&&p.current.rxBps==null?'—':rate((p.current.txBps||0)+(p.current.rxBps||0));$('#bps-caption').textContent=p.current.txBps==null?'Statistiche frame BPQ':'TX '+rate(p.current.txBps)+' / RX '+rate(p.current.rxBps)+' bit/s';$('#radio-scan').textContent=p.current.scan?'● Scansione attiva':p.control.listening?'● Frequenza fissa':'● Porta ferma';$('#radio-modem').textContent='PORT '+p.id+' · '+p.driver;}
|
||||
finally{station.radio=originalRadio;window.bpqRadioControl=originalControl;}
|
||||
document.querySelector('.modem-brand').textContent='PORTE RADIO';
|
||||
document.querySelector('.modem-brand').textContent=BPQI18n.t('PORTE RADIO');
|
||||
const packet=/KISS|AX25|AX\.25/i.test(p.driver),cards=document.querySelectorAll('.telemetry-grid article');cards[1].querySelector('header>span').textContent=packet?'FRAME AX.25':'SNR / BPQ';cards[2].querySelector('header>span').textContent=packet?'TIMEOUT L2':/VARA/i.test(p.driver)?'CPU VARA':'CPU MODEM';cards[2].querySelector('footer').textContent=packet?'Contatore BPQ':'Processo modem · ogni 5 s';
|
||||
if(packet){$('#snr-value').textContent=rate(p.current.txFrames)+' / '+rate(p.current.rxFrames);$('#snr-chart').innerHTML=graph(p.history,['txFrames','rxFrames'],'frame AX25',10);$('#snr-caption').textContent='TX / RX · contatori BPQ';$('#vara-cpu-value').textContent=rate(p.current.timeouts);$('#vara-cpu-chart').innerHTML=graph(p.history,['timeouts'],'timeout L2',5);}
|
||||
}
|
||||
|
||||
+3
-3
@@ -19,7 +19,7 @@ import {ManualForwarding} from './manual-forwarding.mjs';
|
||||
import {forwardingHistory} from './forwarding.mjs';
|
||||
import {Forwarding} from './forwarding.mjs';
|
||||
import {SevenPlus} from './sevenplus.mjs';
|
||||
import {loadConfig,parseConfig,publicConfig,ownCall} from './config.mjs';
|
||||
import {loadConfig,parseConfig,publicConfig,ownCall,authenticateSysop} from './config.mjs';
|
||||
import {readFile, stat,open} from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import {fileURLToPath} from 'node:url';
|
||||
@@ -68,7 +68,7 @@ function mailContext(){return mailReads.run('context',async()=>{if(mailKey&&Date
|
||||
function messages(includeTimes=true){return mailReads.run(includeTimes?'full':'quick',()=>readMessages(includeTimes));}
|
||||
async function readMessages(includeTimes=true){let {key}=await mailContext();let html=await bpq('/WebMail/WMALL?'+key);if(!html.includes('Message List')){mailKey=null;({key}=await mailContext());html=await bpq('/WebMail/WMALL?'+key);if(!html.includes('Message List'))throw new Error('Lista messaggi BPQ non disponibile');}const list=parseMessages(html).filter(m=>m.status!=='K');if(includeTimes)return messageMetadata.enrich(list);for(const m of list.filter(m=>m.type==='P'&&(m.to==='RMS'||m.needsMetadata))){const f=await messageFields(m.id);m.from=f.From||m.from;m.to=f.To||m.to;m.subject=f.Title||m.subject;m.via=f.VIA||m.via;}return list;}
|
||||
function equal(a,b){const aa=Buffer.from(a),bb=Buffer.from(b);return aa.length===bb.length&&timingSafeEqual(aa,bb);}
|
||||
async function authenticate(user,password){const users=parseConfig(await readFile(path.join(root,'BPQ32.cfg'),'utf8')).users;const found=users.find(u=>equal(u.user.toLowerCase(),user.toLowerCase())&&equal(u.password,password)&&u.user===config.sysop.user);return found?{call:found.call,name:found.user,config:publicConfig(config)}:null;}
|
||||
async function authenticate(user,password){const users=parseConfig(await readFile(path.join(root,'BPQ32.cfg'),'utf8')).users;const identity=authenticateSysop(users,user,password,config.sysopUsers);return identity?{...identity,config:publicConfig(config)}:null;}
|
||||
async function body(req){let chunks=[],size=0;for await(const chunk of req){size+=chunk.length;if(size>70000)throw new Error('Messaggio troppo grande');chunks.push(chunk)}return JSON.parse(Buffer.concat(chunks).toString()||'{}');}
|
||||
function json(res,status,data){res.writeHead(status,{'Content-Type':'application/json; charset=utf-8','Cache-Control':'no-store'});res.end(JSON.stringify(data));}
|
||||
function session(req){const token=req.headers.cookie?.match(/(?:^|;\s*)alnode=([a-f0-9]+)/)?.[1];const s=sessions.get(token);if(s&&s.expires>Date.now()){s.expires=Date.now()+8*3600000;return s;}if(token){s?.terminal?.close();sessions.delete(token);}return null;}
|
||||
@@ -203,7 +203,7 @@ const server=http.createServer(async(req,res)=>{
|
||||
if(url.pathname==='/api/winlink/sync'&&req.method==='POST'){if(Date.now()-lastCmsRequest<10000)throw new Error('Sincronizzazione già richiesta. Attendi qualche secondo.');await syncNow(config.cmsPeer||'RMS');lastCmsRequest=Date.now();json(res,200,{ok:true});return;}
|
||||
const readRoute=url.pathname.match(/^\/api\/messages\/(\d+)\/read$/);if(readRoute&&req.method==='POST'){const item=(await messages()).find(m=>m.id===Number(readRoute[1]));if(!item)throw new Error('Messaggio non disponibile');json(res,200,await messageReadState.mark(item));return;}
|
||||
if(/^\/api\/messages\/\d+\/delete$/.test(url.pathname)&&req.method==='POST'){json(res,200,await deleteMessage(Number(url.pathname.split('/')[3])));return;}
|
||||
if(/^\/api\/messages\/\d+$/.test(url.pathname)&&req.method==='GET'){const id=url.pathname.split('/').pop();const {key}=await mailContext();const msg=parseMessage(await bpq('/WebMail/WM?'+key+'&'+id));if(!msg)throw new Error('Messaggio non disponibile');try{const raw=await attachedMessage(Number(id));const text=b2Body(raw.bytes);if(text!==null)msg.text=text.replace(/\r\n|\r/g,'\n');}catch{}json(res,200,{id:Number(id),...msg,...await messageTimes(Number(id))});return;}
|
||||
if(/^\/api\/messages\/\d+$/.test(url.pathname)&&req.method==='GET'){const id=url.pathname.split('/').pop();const {key}=await mailContext();const msg=parseMessage(await bpq('/WebMail/WM?'+key+'&'+id));if(!msg)throw new Error('Messaggio non disponibile');try{const raw=await attachedMessage(Number(id));const text=b2Body(raw.bytes);if(text!==null)msg.text=text.replace(/\r\n|\r/g,'\n');}catch{}const fields=await messageFields(Number(id));json(res,200,{id:Number(id),...msg,to:fields.To||msg.to,via:fields.VIA||msg.via||'',...await messageTimes(Number(id))});return;}
|
||||
if(url.pathname==='/api/messages'&&req.method==='POST'){json(res,201,await sendMessage(await readSubmission(req)));return;}
|
||||
if(url.pathname==='/api/sync'&&req.method==='POST'){await syncNow();json(res,200,{ok:true});return;}
|
||||
json(res,404,{error:'Operazione non disponibile'});return;
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import os from 'node:os';
|
||||
import http from 'node:http';
|
||||
import net from 'node:net';
|
||||
import {spawn} from 'node:child_process';
|
||||
import {once} from 'node:events';
|
||||
import {parseConfig,validateSysopUsers,authenticateSysop} from './config.mjs';
|
||||
|
||||
const accountLines='USER=admin,primary-secret,N0TEST,SYSOP\nUSER=Marco,secondary-secret,N0OTHER,SYSOP\nUSER=guest,guest-secret,N0GUEST,\n';
|
||||
const users=parseConfig(accountLines).users;
|
||||
test('all native SYSOP accounts can log in with their own identity; normal users and wrong passwords cannot',()=>{
|
||||
assert.deepEqual(authenticateSysop(users,'ADMIN','primary-secret'),{name:'admin',call:'N0TEST'});
|
||||
assert.deepEqual(authenticateSysop(users,'marco','secondary-secret'),{name:'Marco',call:'N0OTHER'});
|
||||
for(const [name,password]of [['guest','guest-secret'],['Marco','SECONDARY-SECRET'],['missing','primary-secret']])assert.equal(authenticateSysop(users,name,password),null);
|
||||
});
|
||||
test('optional sysopUsers restricts native SYSOP access case-insensitively and cannot grant normal users access',()=>{
|
||||
const allow=validateSysopUsers(['mArCo','MARCO'],users);assert.deepEqual(allow,['mArCo']);
|
||||
assert.deepEqual(authenticateSysop(users,'Marco','secondary-secret',allow),{name:'Marco',call:'N0OTHER'});
|
||||
assert.equal(authenticateSysop(users,'admin','primary-secret',allow),null);
|
||||
assert.equal(authenticateSysop(users,'Marco','secondary-secret',[]),null);
|
||||
assert.equal(validateSysopUsers(undefined,users),undefined);
|
||||
for(const bad of [null,'Marco',{},[''],[12],['guest'],['missing']])assert.throws(()=>validateSysopUsers(bad,users),/sysopUsers/);
|
||||
});
|
||||
|
||||
const listen=server=>new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));
|
||||
test('HTTP sessions isolate multiple sysops, retain station identity, enforce the allow-list and reread native roles',async()=>{
|
||||
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'bpq-multi-sysop-')),root=path.join(dir,'station');
|
||||
let child;
|
||||
const upstream=http.createServer((req,res)=>res.end('BPQ Ports'));
|
||||
const stop=async()=>{if(child&&child.exitCode===null){child.kill();await once(child,'exit');}child=null;};
|
||||
try{
|
||||
await fs.mkdir(root);await listen(upstream);
|
||||
const native='NODECALL=N0TEST-7\nPORT\nDRIVER=TELNET\nHTTPPORT='+upstream.address().port+'\n'+accountLines+'ENDPORT\n';
|
||||
await fs.writeFile(path.join(root,'BPQ32.cfg'),native);
|
||||
await fs.writeFile(path.join(dir,'package.json'),' {"type":"module"} ');
|
||||
for(const name of await fs.readdir('.'))if(name.endsWith('.mjs')&&!name.endsWith('.test.mjs')&&name!=='test.mjs')await fs.copyFile(name,path.join(dir,name));
|
||||
const start=async extra=>{
|
||||
const probe=net.createServer();await listen(probe);const port=probe.address().port;await new Promise(resolve=>probe.close(resolve));
|
||||
await fs.writeFile(path.join(dir,'console.config.json'),JSON.stringify({bpqRoot:root,port,sysopUser:'admin',...extra}));
|
||||
child=spawn(process.execPath,[path.join(dir,'server.mjs')],{cwd:dir,env:{...process.env,BPQ_ROOT:root,BPQ_CONSOLE_CONFIG:path.join(dir,'console.config.json'),BPQ_CONSOLE_PORT:String(port)},windowsHide:true,stdio:['ignore','pipe','pipe']});
|
||||
let timer;try{await Promise.race([once(child.stdout,'data'),once(child,'exit').then(()=>{throw Error('Fixture server failed');}),new Promise((_,reject)=>{timer=setTimeout(()=>reject(Error('Fixture startup timeout')),8000);})]);}finally{clearTimeout(timer);}
|
||||
const base='http://127.0.0.1:'+port;
|
||||
return {base,login:(user,password)=>fetch(base+'/api/login',{method:'POST',headers:{origin:base,'content-type':'application/json'},body:JSON.stringify({user,password})})};
|
||||
};
|
||||
let client=await start({});
|
||||
const primaryResponse=await client.login('admin','primary-secret'),secondaryResponse=await client.login('MARCO','secondary-secret');
|
||||
assert.equal(primaryResponse.status,200);assert.equal(secondaryResponse.status,200);
|
||||
const primary=await primaryResponse.json(),secondary=await secondaryResponse.json();
|
||||
assert.equal(primary.call,'N0TEST');assert.equal(secondary.call,'N0OTHER');assert.equal(secondary.name,'Marco');
|
||||
assert.equal(secondary.config.call,'N0TEST');assert.equal(secondary.config.nodeCall,'N0TEST-7');
|
||||
assert.notEqual(primary.csrf,secondary.csrf);assert.ok(!JSON.stringify(secondary).includes('secret'));assert.ok(!('sysopUsers' in secondary.config));
|
||||
const primaryCookie=primaryResponse.headers.get('set-cookie').split(';')[0],secondaryCookie=secondaryResponse.headers.get('set-cookie').split(';')[0];
|
||||
assert.notEqual(primaryCookie,secondaryCookie);
|
||||
const session=async cookie=>fetch(client.base+'/api/session',{headers:{cookie}});
|
||||
assert.equal((await (await session(primaryCookie)).json()).call,'N0TEST');
|
||||
assert.equal((await (await session(secondaryCookie)).json()).call,'N0OTHER');
|
||||
const logout=csrf=>fetch(client.base+'/api/logout',{method:'POST',headers:{origin:client.base,cookie:secondaryCookie,'x-csrf-token':csrf}});
|
||||
assert.equal((await logout(primary.csrf)).status,403);assert.equal((await session(secondaryCookie)).status,200);
|
||||
assert.equal((await logout(secondary.csrf)).status,200);assert.equal((await session(secondaryCookie)).status,401);assert.equal((await session(primaryCookie)).status,200);
|
||||
assert.equal((await client.login('guest','guest-secret')).status,401);assert.equal((await client.login('Marco','wrong')).status,401);
|
||||
await stop();client=await start({sysopUsers:['MARCO']});
|
||||
assert.equal((await client.login('admin','primary-secret')).status,401);
|
||||
assert.equal((await client.login('Marco','secondary-secret')).status,200);
|
||||
await fs.writeFile(path.join(root,'BPQ32.cfg'),native.replace('N0OTHER,SYSOP','N0OTHER,'));
|
||||
assert.equal((await client.login('Marco','secondary-secret')).status,401);
|
||||
}finally{
|
||||
await stop();upstream.closeAllConnections();await new Promise(resolve=>upstream.close(resolve));
|
||||
assert.ok(path.resolve(dir).startsWith(path.resolve(os.tmpdir())+path.sep));await fs.rm(dir,{recursive:true,force:true});
|
||||
}
|
||||
});
|
||||
Reference in new issue
Block a user