Fix sysop BBS deletion and keep confirmation errors visible

This commit is contained in:
alberto committed 2026-10-17 15:50:22 +02:00
1 parent 8cb4b6256f
commit 018c0f574e
9 files changed
+126 -15

No files matched your search

+4
View File
@@ -8,6 +8,10 @@ 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. 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.
## 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.
## Winlink attachments ## Winlink attachments
Incoming and queued Winlink messages show an attachment indicator in the list and file cards in the reader. Download original files or preview images, PDFs and plain text; HTML/SVG attachments are shown as text. Binary attachments use BPQ’s native B2 format. Incoming and queued Winlink messages show an attachment indicator in the list and file cards in the reader. Download original files or preview images, PDFs and plain text; HTML/SVG attachments are shown as text. Binary attachments use BPQ’s native B2 format.
+34
View File
@@ -0,0 +1,34 @@
import {parseMessages,decode} from './bpq.mjs';
async function killAsSysop(id,item,bpq){
const status=await bpq('/Mail/Status'),key=status.match(/href=\/Mail\/Msgs\?([^\s>]+)/)?.[1];if(!key)throw Error('Sessione amministrativa BPQ non disponibile');
const html=await bpq('/Mail/MsgDetails?'+key,{method:'POST',body:String(id)});
if(!new RegExp('Message\\s+'+id+'(?!\\d)').test(html))throw Error('BPQ non ha confermato il messaggio da cancellare');
const fields={};for(const match of html.matchAll(/<input\b[^>]*>/gi)){
const name=match[0].match(/\bname=(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i),value=match[0].match(/\bvalue=(?:"([^"]*)"|'([^']*)'|([^\s>]*))/i);
if(name&&value)fields[name[1]??name[2]??name[3]]=decode(value[1]??value[2]??value[3]);
}
const names=['From','To','BID','EFROM','VIA','Title'];
if(names.some(name=>!(name in fields)||/[|\r\n\0]/.test(fields[name])))throw Error('Metadati BPQ non verificabili: cancellazione interrotta');
const typeBlock=html.match(/<select\b[^>]*name=["']?Type["']?[^>]*>([\s\S]*?)<\/select>/i)?.[1];
const selected=typeBlock&&[...typeBlock.matchAll(/<option\b([^>]*)>/gi)].find(m=>/\bselected\b/i.test(m[1]));
const type=selected?.[1].match(/\bvalue=["']?([BPT])/i)?.[1];if(type!==item.type)throw Error('Metadati BPQ non verificabili: cancellazione interrotta');
// MsgSave is the native sysop action. Preserve all editable fields and change
// only Status to K; BPQ clears forwarding bits and saves its own database.
await bpq('/Mail/MsgSave?'+key,{method:'POST',body:[...names.map(name=>fields[name]),type,'K',''].join('|')});
}
export async function deleteNativeMessage(id,bpq,{sysop=false}={}){
if(!Number.isSafeInteger(id)||id<1)throw Error('Messaggio non valido');
// A cached WebMail key may survive a BPQ restart. With an expired key BPQ
// returns a new session's message list instead of executing WMDel.
const page=await bpq('/Webmail'),key=page.match(/WMB\?([^>\s]+)/)?.[1];if(!key)throw Error('WebMail BPQ non disponibile');
const read=async()=>{const html=await bpq('/WebMail/WMALL?'+key);if(!html.includes('Message List'))throw Error('Lista messaggi BPQ non disponibile');return parseMessages(html);};
const visible=message=>message.id===id&&message.status!=='K';
const item=(await read()).find(visible);if(!item)return {ok:true,alreadyDeleted:true};
const response=await bpq('/WebMail/WMDel/'+id+'?'+key);
if(/Not your message|not allowed|permission denied/i.test(response)){
if(!sysop)throw Error('BPQ non autorizza la cancellazione: verifica i permessi sysop della BBS');
await killAsSysop(id,item,bpq);
}
if((await read()).some(visible))throw Error('BPQ non ha confermato la cancellazione');
return {ok:true};
}
+36
View File
@@ -0,0 +1,36 @@
import test from 'node:test';import assert from 'node:assert/strict';import {deleteNativeMessage} from './delete-message.mjs';
const list=(status='N')=>'Message List\r\n<a href=/WebMail/WM?fresh&7> 7</a> 17-Oct B'+status+' 100 '+['ALL','WW','N1TEST'].map(s=>s.padEnd(7)).join(' ')+' Test bulletin\r\n';
test('delete uses a fresh private WebMail session and confirms the message is gone',async()=>{
const calls=[];let killed=false;
const bpq=async url=>{calls.push(url);if(url==='/Webmail')return '<a href=/WebMail/WMB?fresh>Bulls</a>';if(url==='/WebMail/WMALL?fresh')return killed?'Message List':list();if(url==='/WebMail/WMDel/7?fresh'){killed=true;return 'Message #7 Killed';}throw Error('Unexpected or stale WebMail key');};
assert.deepEqual(await deleteNativeMessage(7,bpq),{ok:true});assert.deepEqual(calls,['/Webmail','/WebMail/WMALL?fresh','/WebMail/WMDel/7?fresh','/WebMail/WMALL?fresh']);
});
test('a BPQ permission denial is reported instead of pretending the message was deleted',async()=>{
await assert.rejects(deleteNativeMessage(7,async url=>url==='/Webmail'?'<a href=/WebMail/WMB?fresh>Mail</a>':url.includes('WMDel')?'Not your message':list()),/permessi sysop/);
});
test('a native HTTP 200 or session-redirect page is insufficient if the message remains visible',async()=>{
await assert.rejects(deleteNativeMessage(7,async url=>url==='/Webmail'?'<a href=/WebMail/WMB?fresh>Mail</a>':list()),/non ha confermato/);
});
test('already absent or killed messages are idempotent and never issue another delete',async()=>{
for(const html of ['Message List',list('K')]){const calls=[];const result=await deleteNativeMessage(7,async url=>{calls.push(url);return url==='/Webmail'?'<a href=/WebMail/WMB?fresh>Mail</a>':html;});assert.equal(result.alreadyDeleted,true);assert.ok(!calls.some(url=>url.includes('WMDel')));}
});
test('BPQ may retain the killed row for sysop inspection; status K confirms deletion',async()=>{
let killed=false;assert.deepEqual(await deleteNativeMessage(7,async url=>{if(url==='/Webmail')return '<a href=/WebMail/WMB?fresh>Mail</a>';if(url.includes('WMDel')){killed=true;return 'Killed';}return list(killed?'K':'N');}),{ok:true});
});
test('unverifiable sessions and invalid message IDs cannot issue a deletion',async()=>{
await assert.rejects(deleteNativeMessage(0,async()=>{throw Error('Must not contact BPQ');}),/non valido/);
await assert.rejects(deleteNativeMessage(7,async()=>'<h1>Sign in</h1>'),/WebMail/);
await assert.rejects(deleteNativeMessage(7,async url=>url==='/Webmail'?'<a href=/WebMail/WMB?fresh>Mail</a>':'Sign in'),/Lista messaggi/);
});
test('sysop Console can delete another author bulletin through the native admin action, preserving metadata',async()=>{
let killed=false,save=null;const fields={From:'N1TEST',To:'ALL',BID:'BID_123',EFROM:'',VIA:'WW',Title:'Test & bulletin'};
const bpq=async(url,options)=>{if(url==='/Webmail')return '<a href=/WebMail/WMB?fresh>Mail</a>';if(url.includes('WMALL'))return killed?'Message List':list();if(url.includes('WMDel'))return 'Not your message';if(url==='/Mail/Status')return '<a href=/Mail/Msgs?private>Messages</a>';if(url.startsWith('/Mail/MsgDetails'))return '<h2>Message 7</h2>'+Object.entries(fields).map(([k,v])=>'<input name="'+k+'" value="'+v.replace('&','&amp;')+'">').join('')+'<select name="Type"><option value="P">Personal</option><option value="B" selected>Bulletin</option></select>';if(url.startsWith('/Mail/MsgSave')){save=options.body;killed=true;return 'Saved';}throw Error(url);};
assert.deepEqual(await deleteNativeMessage(7,bpq,{sysop:true}),{ok:true});assert.equal(save,'N1TEST|ALL|BID_123||WW|Test & bulletin|B|K|');
});
test('admin fallback refuses to modify the wrong message or incomplete metadata',async()=>{
let saves=0;const bpq=async url=>{if(url==='/Webmail')return '<a href=/WebMail/WMB?fresh>Mail</a>';if(url.includes('WMALL'))return list();if(url.includes('WMDel'))return 'Not your message';if(url==='/Mail/Status')return '<a href=/Mail/Msgs?admin>Messages</a>';if(url.includes('MsgDetails'))return '<h2>Message 8</h2><input name="From" value="N1TEST">';if(url.includes('MsgSave'))saves++;return '';};
await assert.rejects(deleteNativeMessage(7,bpq,{sysop:true}),/non ha confermato il messaggio/);assert.equal(saves,0);
});
+8 -3
View File
@@ -3,7 +3,7 @@ import fs from 'node:fs/promises';import path from 'node:path';import os from 'n
import {parseAttachments,b2Body} from './attachments.mjs'; import {parseAttachments,b2Body} from './attachments.mjs';
const listen=server=>new Promise(resolve=>server.listen(0,'127.0.0.1',resolve)); const listen=server=>new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));
test('Winlink API uploads to native WebMail, verifies storage, lists and downloads received attachments',async()=>{ test('Winlink API uploads to native WebMail, verifies storage, lists and downloads received attachments',async()=>{
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'bpq-upload-')),root=path.join(dir,'station');let child,stored=null,nativePosts=0,nextId=0; const dir=await fs.mkdtemp(path.join(os.tmpdir(),'bpq-upload-')),root=path.join(dir,'station');let child,stored=null,nativePosts=0,nextId=0,killed=false,adminSaves=0;
const mail=path.join(root,'BPQMailChat','Mail');await fs.mkdir(mail,{recursive:true}); const mail=path.join(root,'BPQMailChat','Mail');await fs.mkdir(mail,{recursive:true});
const server=http.createServer(async(req,res)=>{try{ const server=http.createServer(async(req,res)=>{try{
if(req.url==='/Webmail'){res.end('<a href=/WebMail/WMB?fixture>Mail</a>');return;} if(req.url==='/Webmail'){res.end('<a href=/WebMail/WMB?fixture>Mail</a>');return;}
@@ -15,9 +15,11 @@ test('Winlink API uploads to native WebMail, verifies storage, lists and downloa
const body=Buffer.from(form.get('Msg'));stored=Buffer.concat([Buffer.from('MID: local-fixture\r\nBody: '+body.length+'\r\n'+files.map(f=>'File: '+f.data.length+' '+f.name+'\r\n').join('')+'\r\n'),body,Buffer.from('\r\n'),...files.flatMap(f=>[f.data,Buffer.from('\r\n')])]); const body=Buffer.from(form.get('Msg'));stored=Buffer.concat([Buffer.from('MID: local-fixture\r\nBody: '+body.length+'\r\n'+files.map(f=>'File: '+f.data.length+' '+f.name+'\r\n').join('')+'\r\n'),body,Buffer.from('\r\n'),...files.flatMap(f=>[f.data,Buffer.from('\r\n')])]);
nextId=1;await fs.writeFile(path.join(mail,'m_000001.mes'),stored);res.end('Message Saved');return; nextId=1;await fs.writeFile(path.join(mail,'m_000001.mes'),stored);res.end('Message Saved');return;
} }
if(req.url.startsWith('/WebMail/WMALL')){res.end('Message List\r\n'+(nextId?'<a href=/WebMail/WM?fixture&1> 1</a> 17-Oct PN 100 '+['RMS','','N0TEST'].map(s=>s.padEnd(7)).join(' ')+' Attachment fixture\r\n':''));return;} if(req.url.startsWith('/WebMail/WMDel/')){res.end('Not your message');return;}
if(req.url.startsWith('/Mail/MsgSave')){let payload='';for await(const chunk of req)payload+=chunk;assert.equal(payload,'N0TEST|RMS|BID-fixture||[email protected]|Attachment fixture|P|K|');killed=true;adminSaves++;res.end('Saved');return;}
if(req.url.startsWith('/WebMail/WMALL')){res.end('Message List\r\n'+(nextId?'<a href=/WebMail/WM?fixture&1> 1</a> 17-Oct P'+(killed?'K':'N')+' 100 '+['RMS','','N0TEST'].map(s=>s.padEnd(7)).join(' ')+' Attachment fixture\r\n':''));return;}
if(req.url==='/Mail/Status'){res.end('<a href=/Mail/Msgs?fixture>Messages</a>');return;} if(req.url==='/Mail/Status'){res.end('<a href=/Mail/Msgs?fixture>Messages</a>');return;}
if(req.url.startsWith('/Mail/MsgDetails')){res.end(Object.entries({From:'N0TEST',To:'RMS',Title:'Attachment fixture',VIA:'[email protected]',Sent:'17-Oct 12:00Z',RX:'17-Oct 12:00Z'}).map(([k,v])=>'<input name="'+k+'" value="'+v+'">').join(''));return;} if(req.url.startsWith('/Mail/MsgDetails')){res.end('<h2>Message 1</h2><select name=Type><option selected value=P>P</option></select>'+Object.entries({BID:'BID-fixture',EFROM:'',From:'N0TEST',To:'RMS',Title:'Attachment fixture',VIA:'[email protected]',Sent:'17-Oct 12:00Z',RX:'17-Oct 12:00Z'}).map(([k,v])=>'<input name="'+k+'" value="'+v+'">').join(''));return;}
if(req.url.startsWith('/WebMail/WM?')){res.end('<textarea>From: N0TEST\r\nTo: RMS\r\nTitle: Attachment fixture\r\nType/Status: PN\r\n\r\nNative body with binary attachments stripped by Console</textarea>');return;} if(req.url.startsWith('/WebMail/WM?')){res.end('<textarea>From: N0TEST\r\nTo: RMS\r\nTitle: Attachment fixture\r\nType/Status: PN\r\n\r\nNative body with binary attachments stripped by Console</textarea>');return;}
res.end('BPQ Ports'); res.end('BPQ Ports');
}catch(e){res.statusCode=500;res.end(e.message);}}); }catch(e){res.statusCode=500;res.end(e.message);}});
@@ -45,5 +47,8 @@ test('Winlink API uploads to native WebMail, verifies storage, lists and downloa
const denied=await fetch(base+'/api/messages/1/attachments/0');assert.equal(denied.status,401); const denied=await fetch(base+'/api/messages/1/attachments/0');assert.equal(denied.status,401);
const oversized=new FormData();for(const [key,value]of Object.entries({to:'RMS/[email protected]',subject:'Too big',text:'x'.repeat(30000),type:'P'}))oversized.set(key,value);oversized.append('files',new Blob([Buffer.alloc(60000)]),'large.bin');const rejected=await fetch(base+'/api/messages',{method:'POST',headers,body:oversized});assert.match((await rejected.json()).error,/80 KB/);assert.equal(nativePosts,1); const oversized=new FormData();for(const [key,value]of Object.entries({to:'RMS/[email protected]',subject:'Too big',text:'x'.repeat(30000),type:'P'}))oversized.set(key,value);oversized.append('files',new Blob([Buffer.alloc(60000)]),'large.bin');const rejected=await fetch(base+'/api/messages',{method:'POST',headers,body:oversized});assert.match((await rejected.json()).error,/80 KB/);assert.equal(nativePosts,1);
const badHeaders={...headers,'x-csrf-token':'wrong'};assert.equal((await fetch(base+'/api/messages',{method:'POST',headers:badHeaders,body:form})).status,403);assert.equal(nativePosts,1); const badHeaders={...headers,'x-csrf-token':'wrong'};assert.equal((await fetch(base+'/api/messages',{method:'POST',headers:badHeaders,body:form})).status,403);assert.equal(nativePosts,1);
const deleted=await fetch(base+'/api/messages/1/delete',{method:'POST',headers,body:'{}'});assert.equal(deleted.status,200,await deleted.clone().text());assert.equal((await deleted.json()).ok,true);assert.equal(adminSaves,1);
const remaining=await (await fetch(base+'/api/messages',{headers})).json();assert.equal(remaining.length,0);
const again=await fetch(base+'/api/messages/1/delete',{method:'POST',headers,body:'{}'});assert.equal((await again.json()).alreadyDeleted,true);assert.equal(adminSaves,1);
}finally{if(child&&child.exitCode===null){child.kill();await once(child,'exit');}server.closeAllConnections();await new Promise(resolve=>server.close(resolve));await fs.rm(dir,{recursive:true,force:true});} }finally{if(child&&child.exitCode===null){child.kill();await once(child,'exit');}server.closeAllConnections();await new Promise(resolve=>server.close(resolve));await fs.rm(dir,{recursive:true,force:true});}
}); });
+3 -2
View File
@@ -1,11 +1,12 @@
const $=s=>document.querySelector(s), $$=s=>[...document.querySelectorAll(s)]; const $=s=>document.querySelector(s), $$=s=>[...document.querySelectorAll(s)];
let station={call:'',alias:'',features:{},apps:[]}; let station={call:'',alias:'',features:{},apps:[]};
const deletedMessageIds=new Set();
let csrf='',allMessages=[],dashboardData=null,filter='all',selected=null,page='home',loadGeneration=0; let csrf='',allMessages=[],dashboardData=null,filter='all',selected=null,page='home',loadGeneration=0;
const esc=v=>String(v??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c])); const esc=v=>String(v??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
async function api(url,options={}){const r=await fetch('/api'+url,{...options,headers:{...(options.body instanceof FormData?{}:{'Content-Type':'application/json'}),...(options.method==='POST'?{'X-CSRF-Token':csrf}:{}),...options.headers}});const data=await r.json();if(!r.ok){if(r.status===401&&url!=='/login')showLogin();throw new Error(data.error||'Richiesta fallita')}return data;} async function api(url,options={}){const r=await fetch('/api'+url,{...options,headers:{...(options.body instanceof FormData?{}:{'Content-Type':'application/json'}),...(options.method==='POST'?{'X-CSRF-Token':csrf}:{}),...options.headers}});const data=await r.json();if(!r.ok){if(r.status===401&&url!=='/login')showLogin();throw new Error(data.error||'Richiesta fallita')}return data;}
function toast(text){$('#toast').textContent=text;$('#toast').hidden=false;clearTimeout(toast.timer);toast.timer=setTimeout(()=>$('#toast').hidden=true,6500);} function toast(text){$('#toast').textContent=text;$('#toast').hidden=false;clearTimeout(toast.timer);toast.timer=setTimeout(()=>$('#toast').hidden=true,6500);}
function showLogin(){document.title='BPQ Console';$('#shell').hidden=true;$('#login').hidden=false;csrf='';} function showLogin(){document.title='BPQ Console';$('#shell').hidden=true;$('#login').hidden=false;csrf='';}
function showShell(user){station=user.config;applyStation(user);csrf=user.csrf;$('#login').hidden=true;$('#shell').hidden=false;loadDashboard();if(station.features.bbs)loadMessages();document.dispatchEvent(new Event('station-ready'));} function showShell(user){deletedMessageIds.clear();station=user.config;applyStation(user);csrf=user.csrf;$('#login').hidden=true;$('#shell').hidden=false;loadDashboard();if(station.features.bbs)loadMessages();document.dispatchEvent(new Event('station-ready'));}
function logTime(value){if(!value)return '—';const m=value.match(/^(\d{2})(\d{2})(\d{2}) (\d{2}:\d{2}:\d{2})$/);if(!m)return value;return new Date(`20${m[1]}-${m[2]}-${m[3]}T${m[4]}Z`).toLocaleTimeString(BPQI18n.locale(),{hour:'2-digit',minute:'2-digit'});} function logTime(value){if(!value)return '—';const m=value.match(/^(\d{2})(\d{2})(\d{2}) (\d{2}:\d{2}:\d{2})$/);if(!m)return value;return new Date(`20${m[1]}-${m[2]}-${m[3]}T${m[4]}Z`).toLocaleTimeString(BPQI18n.locale(),{hour:'2-digit',minute:'2-digit'});}
function categoryLabel(m){return m.type==='P'?BPQI18n.t('PERSONALE'):m.to||BPQI18n.t('BOLLETTINO')} function categoryLabel(m){return m.type==='P'?BPQI18n.t('PERSONALE'):m.to||BPQI18n.t('BOLLETTINO')}
function friendlyActivity(text){if(/Failure with/.test(text))return 'il nodo remoto non ha risposto alla chiamata';if(/Connecting to BBS/.test(text))return 'Chiamata radio verso il nodo remoto avviata';if(/Incoming Connect/.test(text))return 'il nodo remoto si è collegato alla nostra BBS';if(/Uncompressing Message/.test(text))return 'Ricevuto e salvato un nuovo bollettino';if(/Disconnected/.test(text))return 'Sessione con il nodo remoto terminata';return text;} function friendlyActivity(text){if(/Failure with/.test(text))return 'il nodo remoto non ha risposto alla chiamata';if(/Connecting to BBS/.test(text))return 'Chiamata radio verso il nodo remoto avviata';if(/Incoming Connect/.test(text))return 'il nodo remoto si è collegato alla nostra BBS';if(/Uncompressing Message/.test(text))return 'Ricevuto e salvato un nuovo bollettino';if(/Disconnected/.test(text))return 'Sessione con il nodo remoto terminata';return text;}
@@ -16,7 +17,7 @@ $$('[data-page]').forEach(b=>b.addEventListener('click',()=>navigate(b.dataset.p
$('#login-form').addEventListener('submit',async e=>{e.preventDefault();const b=e.target.querySelector('button');b.disabled=true;$('#login-error').textContent='';try{const user=await api('/login',{method:'POST',body:JSON.stringify(Object.fromEntries(new FormData(e.target)))});e.target.password.value='';showShell(user);}catch(err){$('#login-error').textContent=err.message}finally{b.disabled=false}}); $('#login-form').addEventListener('submit',async e=>{e.preventDefault();const b=e.target.querySelector('button');b.disabled=true;$('#login-error').textContent='';try{const user=await api('/login',{method:'POST',body:JSON.stringify(Object.fromEntries(new FormData(e.target)))});e.target.password.value='';showShell(user);}catch(err){$('#login-error').textContent=err.message}finally{b.disabled=false}});
$('#logout').onclick=async()=>{try{await api('/logout',{method:'POST',body:'{}'})}finally{showLogin()}}; $('#logout').onclick=async()=>{try{await api('/logout',{method:'POST',body:'{}'})}finally{showLogin()}};
async function loadDashboard(){try{const d=await api('/dashboard');dashboardData=d;$('#connection').textContent=d.errors.length?'● Dati parziali':'● BPQ connesso';$('#notice').hidden=!d.errors.length;$('#notice').textContent=d.errors.join(' · ');$('#k-messages').textContent=d.counts.messages;$('#nav-count').textContent=d.counts.messages;$('#k-message-detail').textContent=`${d.counts.bulletins} bollettini · ${d.counts.personal} personali`;$('#k-nodes').textContent=d.nodes.length;$('#k-routes').textContent=d.routes.filter(r=>r.active).length;$('#k-sync').textContent=logTime(d.sync?.at);$('#k-sync-detail').textContent=d.sync?`${d.sync.received} ${d.sync.received===1?'messaggio ricevuto':'messaggi ricevuti'} · ${mailTimezone()}`:'Nessuno rilevato oggi';const r=d.radio;$('#radio-freq').textContent=r?.frequency||'—';$('#radio-status').textContent=r?.connected?'MODEM ONLINE':'NON DISPONIBILE';$('#radio-modem').textContent=r?.connected?(station.radio?.driver||'Modem')+' '+r.mode:'Non collegato';$('#radio-channel').textContent=r?(r.busy?'Occupato':'Libero'):'—';$('#radio-snr').textContent=r?r.snr+' dB':'—';$('#radio-scan').textContent=r?.scanning?'● Scansione attiva':r?.state&&r.state!=='Free'?'● '+r.state:'Scansione non rilevata';$('#updated').textContent='Aggiornato '+new Date(d.updatedAt).toLocaleTimeString(BPQI18n.locale(),{hour:'2-digit',minute:'2-digit'});$('#routes').innerHTML=d.routes.map(r=>`<tr><td>${esc(r.call)}</td><td><span class="tag">${r.active?'ATTIVO':'INATTIVO'}</span></td><td>${esc(r.port)}</td><td>${r.quality}</td><td>${r.nodes}</td><td>${r.frames}</td><td>${r.retries}</td></tr>`).join('')||'<tr><td colspan="7">Nessuna rotta disponibile</td></tr>';$('#nodes').innerHTML=d.nodes.map(n=>{const [alias,call]=n.split(':');return `<div class="node"><strong>${esc(alias)}</strong><small>${esc(call)}</small></div>`}).join('');$('#node-total').textContent=d.nodes.length+' destinazioni';}catch(err){$('#connection').textContent='● Connessione assente';$('#notice').hidden=false;$('#notice').textContent=err.message;}} async function loadDashboard(){try{const d=await api('/dashboard');dashboardData=d;$('#connection').textContent=d.errors.length?'● Dati parziali':'● BPQ connesso';$('#notice').hidden=!d.errors.length;$('#notice').textContent=d.errors.join(' · ');$('#k-messages').textContent=d.counts.messages;$('#nav-count').textContent=d.counts.messages;$('#k-message-detail').textContent=`${d.counts.bulletins} bollettini · ${d.counts.personal} personali`;$('#k-nodes').textContent=d.nodes.length;$('#k-routes').textContent=d.routes.filter(r=>r.active).length;$('#k-sync').textContent=logTime(d.sync?.at);$('#k-sync-detail').textContent=d.sync?`${d.sync.received} ${d.sync.received===1?'messaggio ricevuto':'messaggi ricevuti'} · ${mailTimezone()}`:'Nessuno rilevato oggi';const r=d.radio;$('#radio-freq').textContent=r?.frequency||'—';$('#radio-status').textContent=r?.connected?'MODEM ONLINE':'NON DISPONIBILE';$('#radio-modem').textContent=r?.connected?(station.radio?.driver||'Modem')+' '+r.mode:'Non collegato';$('#radio-channel').textContent=r?(r.busy?'Occupato':'Libero'):'—';$('#radio-snr').textContent=r?r.snr+' dB':'—';$('#radio-scan').textContent=r?.scanning?'● Scansione attiva':r?.state&&r.state!=='Free'?'● '+r.state:'Scansione non rilevata';$('#updated').textContent='Aggiornato '+new Date(d.updatedAt).toLocaleTimeString(BPQI18n.locale(),{hour:'2-digit',minute:'2-digit'});$('#routes').innerHTML=d.routes.map(r=>`<tr><td>${esc(r.call)}</td><td><span class="tag">${r.active?'ATTIVO':'INATTIVO'}</span></td><td>${esc(r.port)}</td><td>${r.quality}</td><td>${r.nodes}</td><td>${r.frames}</td><td>${r.retries}</td></tr>`).join('')||'<tr><td colspan="7">Nessuna rotta disponibile</td></tr>';$('#nodes').innerHTML=d.nodes.map(n=>{const [alias,call]=n.split(':');return `<div class="node"><strong>${esc(alias)}</strong><small>${esc(call)}</small></div>`}).join('');$('#node-total').textContent=d.nodes.length+' destinazioni';}catch(err){$('#connection').textContent='● Connessione assente';$('#notice').hidden=false;$('#notice').textContent=err.message;}}
async function loadMessages(){if(!station.features.bbs)return;try{allMessages=await api('/messages');const current=$('#category').value;const categories=[...new Set(allMessages.filter(m=>m.type==='B').map(m=>m.to))].sort();$('#category').innerHTML='<option value="">Tutte le categorie</option>'+categories.map(c=>`<option>${esc(c)}</option>`).join('');$('#category').value=current;renderMessages();}catch(err){toast(err.message)}} async function loadMessages(){if(!station.features.bbs)return;try{allMessages=(await api('/messages')).filter(m=>!deletedMessageIds.has(m.id));const current=$('#category').value;const categories=[...new Set(allMessages.filter(m=>m.type==='B').map(m=>m.to))].sort();$('#category').innerHTML='<option value="">Tutte le categorie</option>'+categories.map(c=>`<option>${esc(c)}</option>`).join('');$('#category').value=current;renderMessages();}catch(err){toast(err.message)}}
function mailDate(m,kind='received'){const value=kind==='sent'?m.createdAt:(m.receivedAt||m.createdAt);if(!value)return m.date||'—';return new Date(value).toLocaleString(BPQI18n.locale(),{day:'2-digit',month:'2-digit',hour:'2-digit',minute:'2-digit'});} function mailDate(m,kind='received'){const value=kind==='sent'?m.createdAt:(m.receivedAt||m.createdAt);if(!value)return m.date||'—';return new Date(value).toLocaleString(BPQI18n.locale(),{day:'2-digit',month:'2-digit',hour:'2-digit',minute:'2-digit'});}
function mailTimezone(){const minutes=-new Date().getTimezoneOffset();return 'UTC'+(minutes>=0?'+':'-')+String(Math.floor(Math.abs(minutes)/60)).padStart(2,'0')+':'+String(Math.abs(minutes)%60).padStart(2,'0');} function mailTimezone(){const minutes=-new Date().getTimezoneOffset();return 'UTC'+(minutes>=0?'+':'-')+String(Math.floor(Math.abs(minutes)/60)).padStart(2,'0')+':'+String(Math.abs(minutes)%60).padStart(2,'0');}
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 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('');}
+2 -1
View File
@@ -623,7 +623,8 @@ Campo allegato non valido|Invalid attachment field
Gli allegati in uscita sono disponibili per le email Winlink|Outgoing attachments are available for Winlink emails Gli allegati in uscita sono disponibili per le email Winlink|Outgoing attachments are available for Winlink emails
BPQ ha salvato il messaggio ma gli allegati non corrispondono. Controlla la coda prima di riprovare.|BPQ saved the message but the attachments do not match. Check the queue before retrying.`; BPQ ha salvato il messaggio ma gli allegati non corrispondono. Controlla la coda prima di riprovare.|BPQ saved the message but the attachments do not match. Check the queue before retrying.`;
const sizeCopy='Testo e allegati superano 80 KB complessivi|Message text and attachments exceed 80 KB total\nMessaggio troppo grande per il server HTTP BPQ|Message too large for the BPQ HTTP server'; const sizeCopy='Testo e allegati superano 80 KB complessivi|Message text and attachments exceed 80 KB total\nMessaggio troppo grande per il server HTTP BPQ|Message too large for the BPQ HTTP server';
const dictionary=new Map((entries.trim()+'\n'+uploadCopy+'\n'+sizeCopy).split('\n').map(line=>line.split('|'))); const deleteCopy='Sessione amministrativa BPQ non disponibile|BPQ admin session unavailable\nBPQ non ha confermato il messaggio da cancellare|BPQ did not confirm the message selected for deletion\nMetadati BPQ non verificabili: cancellazione interrotta|BPQ metadata could not be verified: deletion stopped\nMessaggio non valido|Invalid message\nBPQ non autorizza la cancellazione: verifica i permessi sysop della BBS|BPQ denied deletion: check the BBS sysop permissions\nBPQ non ha risposto in tempo. Aggiorna l’elenco prima di riprovare.|BPQ did not respond in time. Refresh the list before retrying.';
const dictionary=new Map((entries.trim()+'\n'+uploadCopy+'\n'+sizeCopy+'\n'+deleteCopy).split('\n').map(line=>line.split('|')));
function resolveLanguage(preference=null,languages=[]){ function resolveLanguage(preference=null,languages=[]){
if(preference==='it'||preference==='en')return preference; if(preference==='it'||preference==='en')return preference;
// The first browser language is the user's preferred UI language; English is the fallback. // The first browser language is the user's preferred UI language; English is the fallback.
+14 -4
View File
@@ -6,7 +6,7 @@ async function wlLoad(fresh=false){
if(!csrf)return;if(fresh)wlRefreshVersion++; if(!csrf)return;if(fresh)wlRefreshVersion++;
if(wlLoadTask){if(!fresh)return wlLoadTask;await wlLoadTask;return wlLoad();} if(wlLoadTask){if(!fresh)return wlLoadTask;await wlLoadTask;return wlLoad();}
const version=wlRefreshVersion,call=station.call; const version=wlRefreshVersion,call=station.call;
const task=(async()=>{try{const data=await api('/winlink');if(version!==wlRefreshVersion||!csrf||station.call!==call)return;wlData=data;$('#wl-sync-state').textContent=data.sync.text;$('#wl-sync-state').className='wl-state '+data.sync.state;$('#wl-sync-time').textContent=data.sync.at?logTime(data.sync.at)+' · '+mailTimezone():'';wlRender();}catch(e){if(version===wlRefreshVersion)$('#wl-sync-state').textContent=e.message;}})(); const task=(async()=>{try{const data=await api('/winlink');if(version!==wlRefreshVersion||!csrf||station.call!==call)return;data.messages=data.messages.filter(m=>!deletedMessageIds.has(m.id));wlData=data;$('#wl-sync-state').textContent=data.sync.text;$('#wl-sync-state').className='wl-state '+data.sync.state;$('#wl-sync-time').textContent=data.sync.at?logTime(data.sync.at)+' · '+mailTimezone():'';wlRender();}catch(e){if(version===wlRefreshVersion)$('#wl-sync-state').textContent=e.message;}})();
wlLoadTask=task;try{await task;}finally{if(wlLoadTask===task)wlLoadTask=null;} wlLoadTask=task;try{await task;}finally{if(wlLoadTask===task)wlLoadTask=null;}
} }
@@ -19,7 +19,17 @@ $('#wl-compose').onclick=()=>wlNew();$('#compose').addEventListener('close',()=>
$('#compose-form').addEventListener('submit',e=>{if(!wlCompose)return;const field=e.target.elements.to;let address=field.value.trim().replace(/^RMS[/:]/i,'');if(!address.includes('@'))address+='@WINLINK.ORG';if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(address)){e.preventDefault();e.stopImmediatePropagation();$('#compose-error').textContent='Inserisci un nominativo Winlink o un indirizzo email valido';return;}field.value='RMS/'+address;e.target.elements.type.value='P';},true); $('#compose-form').addEventListener('submit',e=>{if(!wlCompose)return;const field=e.target.elements.to;let address=field.value.trim().replace(/^RMS[/:]/i,'');if(!address.includes('@'))address+='@WINLINK.ORG';if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(address)){e.preventDefault();e.stopImmediatePropagation();$('#compose-error').textContent='Inserisci un nominativo Winlink o un indirizzo email valido';return;}field.value='RMS/'+address;e.target.elements.type.value='P';},true);
$('#wl-sync').onclick=async()=>{const b=$('#wl-sync');b.disabled=true;try{await window.bpqSync.start({kind:'winlink-internet'});$('#wl-sync-state').textContent='Sincronizzazione richiesta…';setTimeout(wlLoad,1500);setTimeout(async()=>{await wlLoad();await loadMessages()},5000);}catch(e){toast(e.message)}finally{setTimeout(()=>b.disabled=false,10000)}}; $('#wl-sync').onclick=async()=>{const b=$('#wl-sync');b.disabled=true;try{await window.bpqSync.start({kind:'winlink-internet'});$('#wl-sync-state').textContent='Sincronizzazione richiesta…';setTimeout(wlLoad,1500);setTimeout(async()=>{await wlLoad();await loadMessages()},5000);}catch(e){toast(e.message)}finally{setTimeout(()=>b.disabled=false,10000)}};
setInterval(()=>{if(csrf&&page==='winlink')wlLoad()},5000); setInterval(()=>{if(csrf&&page==='winlink')wlLoad()},5000);
const deleteDialog=document.createElement('dialog');deleteDialog.innerHTML='<h2>Eliminare il messaggio?</h2><p id="delete-subject" class="delete-subject"></p><p class="delete-note">Verrà rimosso dalla BBS locale di BPQ. Una email già inviata non può essere richiamata.</p><footer><button id="delete-cancel" class="secondary">Annulla</button><button id="delete-confirm" class="danger">Elimina messaggio</button></footer>';document.body.append(deleteDialog);let deleteId=null; const deleteDialog=document.createElement('dialog');deleteDialog.innerHTML='<h2>Eliminare il messaggio?</h2><p id="delete-subject" class="delete-subject"></p><p class="delete-note">Verrà rimosso dalla BBS locale di BPQ. Una email già inviata non può essere richiamata.</p><p id="delete-error" class="error" role="alert" hidden></p><footer><button id="delete-cancel" class="secondary">Annulla</button><button id="delete-confirm" class="danger">Elimina messaggio</button></footer>';document.body.append(deleteDialog);let deleteId=null,deleting=false;
function askDelete(id,subject){deleteId=id;$('#delete-subject').textContent='#'+id+' · '+subject;deleteDialog.showModal()} function askDelete(id,subject){if(deleting)return;deleteId=id;$('#delete-error').hidden=true;$('#delete-error').textContent='';$('#delete-subject').textContent='#'+id+' · '+subject;deleteDialog.showModal()}
$('#delete-cancel').onclick=()=>deleteDialog.close();$('#delete-confirm').onclick=async()=>{const b=$('#delete-confirm');b.disabled=true;try{await api('/messages/'+deleteId+'/delete',{method:'POST',body:'{}'});deleteDialog.close();if(selected===deleteId){selected=null;$('#reader').innerHTML='<div class="reader-empty"><h2>Messaggio eliminato</h2></div>'}if(wlSelected===deleteId){wlSelected=null;wlGeneration++;$('#wl-reader').innerHTML='<div class="reader-empty"><h2>Email eliminata</h2></div>'}await loadMessages();await wlLoad(true);loadDashboard();toast('Messaggio #'+deleteId+' eliminato da BPQ');}catch(e){toast(e.message)}finally{b.disabled=false}}; $('#delete-cancel').onclick=()=>{if(!deleting)deleteDialog.close();};deleteDialog.addEventListener('cancel',e=>{if(deleting)e.preventDefault();});
$('#delete-confirm').onclick=async()=>{
if(deleting||!deleteId)return;const id=deleteId,b=$('#delete-confirm');deleting=true;b.disabled=true;b.textContent='Eliminazione…';$('#delete-cancel').disabled=true;$('#delete-error').hidden=true;
try{await api('/messages/'+id+'/delete',{method:'POST',body:'{}',signal:AbortSignal.timeout(30000)});
deletedMessageIds.add(id);allMessages=allMessages.filter(m=>m.id!==id);if(wlData)wlData.messages=wlData.messages.filter(m=>m.id!==id);wlRefreshVersion++;
deleteDialog.close();if(selected===id){selected=null;loadGeneration++;$('#reader').innerHTML='<div class="reader-empty"><h2>Messaggio eliminato</h2></div>';}if(wlSelected===id){wlSelected=null;wlGeneration++;$('#wl-reader').innerHTML='<div class="reader-empty"><h2>Email eliminata</h2></div>';}
renderMessages();wlRender();toast('Messaggio #'+id+' eliminato da BPQ');loadMessages();wlLoad(true);loadDashboard();
}catch(e){$('#delete-error').hidden=false;$('#delete-error').textContent=e.name==='TimeoutError'?'BPQ non ha risposto in tempo. Aggiorna l’elenco prima di riprovare.':e.message;}
finally{deleting=false;b.disabled=false;b.textContent='Elimina messaggio';$('#delete-cancel').disabled=false;}
};
const wlOldRead=readMessage;readMessage=async function(id){await wlOldRead(id);if(selected!==id)return;const footer=$('#reader .reader-footer');if(!footer)return;const b=document.createElement('button');b.className='danger';b.textContent='Elimina';b.onclick=()=>askDelete(id,allMessages.find(m=>m.id===id)?.subject||'Messaggio');footer.append(b);}; const wlOldRead=readMessage;readMessage=async function(id){await wlOldRead(id);if(selected!==id)return;const footer=$('#reader .reader-footer');if(!footer)return;const b=document.createElement('button');b.className='danger';b.textContent='Elimina';b.onclick=()=>askDelete(id,allMessages.find(m=>m.id===id)?.subject||'Messaggio');footer.append(b);};
+6 -3
View File
@@ -1,3 +1,4 @@
import {deleteNativeMessage} from './delete-message.mjs';
import {readSubmission,outgoingForm,verifySavedAttachments,uploadLimits} from './mail-upload.mjs'; import {readSubmission,outgoingForm,verifySavedAttachments,uploadLimits} from './mail-upload.mjs';
import {SyncOperations} from './sync-operations.mjs'; import {SyncOperations} from './sync-operations.mjs';
import {RadioControl} from './radio-control.mjs'; import {RadioControl} from './radio-control.mjs';
@@ -58,7 +59,7 @@ async function bpqRequest(url, options={}) {
} }
function mailContext(){return mailReads.run('context',async()=>{if(mailKey&&Date.now()-mailKeyAt<1800000)return {key:mailKey};const html=await bpq('/Webmail');const key=html.match(/WMB\?([^>\s]+)/)?.[1];if(!key)throw new Error('WebMail BPQ non disponibile');mailKey=key;mailKeyAt=Date.now();return {html,key};});} function mailContext(){return mailReads.run('context',async()=>{if(mailKey&&Date.now()-mailKeyAt<1800000)return {key:mailKey};const html=await bpq('/Webmail');const key=html.match(/WMB\?([^>\s]+)/)?.[1];if(!key)throw new Error('WebMail BPQ non disponibile');mailKey=key;mailKeyAt=Date.now();return {html,key};});}
function messages(includeTimes=true){return mailReads.run(includeTimes?'full':'quick',()=>readMessages(includeTimes));} 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);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;} 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);} 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 found=users.find(u=>equal(u.user.toLowerCase(),user.toLowerCase())&&equal(u.password,password)&&u.user===config.sysop.user);return found?{call:found.call,name:found.user,config:publicConfig(config)}:null;}
async function body(req){let chunks=[],size=0;for await(const chunk of req){size+=chunk.length;if(size>70000)throw new Error('Messaggio troppo grande');chunks.push(chunk)}return JSON.parse(Buffer.concat(chunks).toString()||'{}');} 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()||'{}');}
@@ -95,10 +96,12 @@ async function readMessageFields(id,retry=true){let cached=metadataCache.get(id)
async function messageAttachmentSummary(id){let file;try{file=await open(path.join(root,'BPQMailChat','Mail','m_'+String(id).padStart(6,'0')+'.mes'),'r');const header=Buffer.alloc(65540);const {bytesRead}=await file.read(header,0,header.length,0);return attachmentSummary(header.subarray(0,bytesRead));}catch{return {attachmentCount:0,attachmentBytes:0};}finally{await file?.close();}} async function messageAttachmentSummary(id){let file;try{file=await open(path.join(root,'BPQMailChat','Mail','m_'+String(id).padStart(6,'0')+'.mes'),'r');const header=Buffer.alloc(65540);const {bytesRead}=await file.read(header,0,header.length,0);return attachmentSummary(header.subarray(0,bytesRead));}catch{return {attachmentCount:0,attachmentBytes:0};}finally{await file?.close();}}
async function mailMetadata(list){const out=[];for(const item of list.filter(m=>m.type==='P')){const f=await messageFields(item.id);const m={...item,from:f.From||item.from,to:f.To||item.to,subject:f.Title||item.subject};const via=f.VIA||m.via,emailFrom=f.EFROM||'';if(m.to==='RMS'||m.from==='RMS'||/WINLINK|@/i.test(via+emailFrom)){const full={...m,via,emailFrom,address:m.to==='RMS'?via:m.to,fromAddress:emailFrom?(emailFrom.startsWith('@')?m.from+emailFrom:emailFrom):m.from};out.push({...full,...await messageAttachmentSummary(m.id),direction:mailDirection(full,config.sysop.call),folder:mailFolder(full,config.sysop.call)});}}return out;} async function mailMetadata(list){const out=[];for(const item of list.filter(m=>m.type==='P')){const f=await messageFields(item.id);const m={...item,from:f.From||item.from,to:f.To||item.to,subject:f.Title||item.subject};const via=f.VIA||m.via,emailFrom=f.EFROM||'';if(m.to==='RMS'||m.from==='RMS'||/WINLINK|@/i.test(via+emailFrom)){const full={...m,via,emailFrom,address:m.to==='RMS'?via:m.to,fromAddress:emailFrom?(emailFrom.startsWith('@')?m.from+emailFrom:emailFrom):m.from};out.push({...full,...await messageAttachmentSummary(m.id),direction:mailDirection(full,config.sysop.call),folder:mailFolder(full,config.sysop.call)});}}return out;}
async function winlink(){const list=await mailMetadata(await messages(false));for(const m of list)Object.assign(m,await messageTimes(m.id));const today=new Date().toLocaleDateString('sv-SE',{timeZone:'UTC'}).replaceAll('-','').slice(2);let sync=cmsStatus('');try{sync=cmsStatus(await readFile(path.join(root,'Logs',`log_${today}_BBS.txt`),'utf8'));}catch{}const radioSession=winlinkRadio.snapshot();const history=forwardingHistory(await forwarding.logs().catch(()=>''),config.cmsPeer||'RMS');const last=history[0];const radioLatest=radioSession&&(radioSession.restoring||last&&Math.abs(Date.parse(last.startedAt)-Date.parse(radioSession.startedAt))<5000);return {messages:list,sync,account:config.sysop.call.replace(/-\d+$/,'')+'@winlink.org',requestedAt:lastCmsRequest||null,radioSession,transport:radioLatest?'radio':'internet',radioSupported:Boolean(config.radio&&(modemFamily(config.radio.driver)||packetPort(config))&&config.winlinkRadio?.catControl),modem:config.radio?.driver||null};} async function winlink(){const list=await mailMetadata(await messages(false));for(const m of list)Object.assign(m,await messageTimes(m.id));const today=new Date().toLocaleDateString('sv-SE',{timeZone:'UTC'}).replaceAll('-','').slice(2);let sync=cmsStatus('');try{sync=cmsStatus(await readFile(path.join(root,'Logs',`log_${today}_BBS.txt`),'utf8'));}catch{}const radioSession=winlinkRadio.snapshot();const history=forwardingHistory(await forwarding.logs().catch(()=>''),config.cmsPeer||'RMS');const last=history[0];const radioLatest=radioSession&&(radioSession.restoring||last&&Math.abs(Date.parse(last.startedAt)-Date.parse(radioSession.startedAt))<5000);return {messages:list,sync,account:config.sysop.call.replace(/-\d+$/,'')+'@winlink.org',requestedAt:lastCmsRequest||null,radioSession,transport:radioLatest?'radio':'internet',radioSupported:Boolean(config.radio&&(modemFamily(config.radio.driver)||packetPort(config))&&config.winlinkRadio?.catControl),modem:config.radio?.driver||null};}
async function deleteMessage(id){const list=await messages();if(!list.some(m=>m.id===id))throw new Error('Messaggio non presente');const {key}=await mailContext();await bpq('/WebMail/WMDel/'+id+'?'+key);metadataCache.delete(id);timestampCache.delete(id);messageMetadata.invalidate(id);metadataReads.invalidate(id);mailReads.clear();if((await messages()).some(m=>m.id===id))throw new Error('BPQ non ha confermato la cancellazione');return {ok:true};} function deleteMessage(id){return enqueueMailWrite(async()=>{const result=await deleteNativeMessage(id,bpq,{sysop:true});metadataCache.delete(id);timestampCache.delete(id);messageMetadata.invalidate(id);metadataReads.invalidate(id);mailReads.clear();mailKey=null;return result;});}
async function attachedMessage(id){const visible=await messages(false);const item=visible.find(m=>m.id===id);if(!item)throw new Error('Messaggio non disponibile');const file=path.join(root,'BPQMailChat','Mail','m_'+String(id).padStart(6,'0')+'.mes');const info=await stat(file);if(info.size>32*1024*1024)throw new Error('Messaggio troppo grande per il download web (32 MB)');const bytes=await readFile(file);const files=parseAttachments(bytes);const rebuilt=await sevenPlus.forMessage(id,visible);if(rebuilt?.file)files.push({...rebuilt.file,index:files.length});const encoded=item.subject.match(/^7\+\s+(.+?)\s+(\d+)\/(\d+)$/i);return {item,bytes,files,encoded:rebuilt?.metadata||(encoded?{name:safeName(encoded[1]),part:Number(encoded[2]),total:Number(encoded[3]),state:'unavailable'}:null)};} async function attachedMessage(id){const visible=await messages(false);const item=visible.find(m=>m.id===id);if(!item)throw new Error('Messaggio non disponibile');const file=path.join(root,'BPQMailChat','Mail','m_'+String(id).padStart(6,'0')+'.mes');const info=await stat(file);if(info.size>32*1024*1024)throw new Error('Messaggio troppo grande per il download web (32 MB)');const bytes=await readFile(file);const files=parseAttachments(bytes);const rebuilt=await sevenPlus.forMessage(id,visible);if(rebuilt?.file)files.push({...rebuilt.file,index:files.length});const encoded=item.subject.match(/^7\+\s+(.+?)\s+(\d+)\/(\d+)$/i);return {item,bytes,files,encoded:rebuilt?.metadata||(encoded?{name:safeName(encoded[1]),part:Number(encoded[2]),total:Number(encoded[3]),state:'unavailable'}:null)};}
let messageWriteQueue=Promise.resolve(); let messageWriteQueue=Promise.resolve();
function sendMessage(data){const write=messageWriteQueue.then(()=>writeMessage(data));messageWriteQueue=write.catch(()=>{});return write;} function enqueueMailWrite(work){const write=messageWriteQueue.then(work);messageWriteQueue=write.catch(()=>{});return write;}
function sendMessage(data){return enqueueMailWrite(()=>writeMessage(data));}
async function writeMessage(data){ async function writeMessage(data){
const to=String(data.to||'').trim().toUpperCase(),subject=String(data.subject||'').trim(),text=String(data.text||'').trim(),type=String(data.type||'P'); const to=String(data.to||'').trim().toUpperCase(),subject=String(data.subject||'').trim(),text=String(data.text||'').trim(),type=String(data.type||'P');
if(!/^[A-Z0-9][A-Z0-9@.\/#_-]{1,79}$/.test(to)||!subject||subject.length>80||/[\x00-\x1f\x7f]/.test(subject)||!text||text.includes('\0')||Buffer.byteLength(text)>32000||!['P','B'].includes(type))throw new Error('Controlla destinatario, oggetto (max 80 caratteri) e testo (max 32 KB)'); if(!/^[A-Z0-9][A-Z0-9@.\/#_-]{1,79}$/.test(to)||!subject||subject.length>80||/[\x00-\x1f\x7f]/.test(subject)||!text||text.includes('\0')||Buffer.byteLength(text)>32000||!['P','B'].includes(type))throw new Error('Controlla destinatario, oggetto (max 80 caratteri) e testo (max 32 KB)');
+19 -2
View File
@@ -1,10 +1,10 @@
import test from 'node:test';import assert from 'node:assert/strict';import vm from 'node:vm';import {readFileSync} from 'node:fs'; import test from 'node:test';import assert from 'node:assert/strict';import vm from 'node:vm';import {readFileSync} from 'node:fs';
const source=readFileSync(new URL('./public/winlink.js',import.meta.url),'utf8'); const source=readFileSync(new URL('./public/winlink.js',import.meta.url),'utf8');
function element(){const classes=new Set();return {dataset:{},value:'',textContent:'',innerHTML:'',hidden:false,disabled:false,children:[{},{},{}],classList:{toggle(name,on){on?classes.add(name):classes.delete(name);},contains:name=>classes.has(name)},attributes:{},setAttribute(key,value){this.attributes[key]=value;},addEventListener(){},append(){},insertBefore(){},closest(){return element();}};} function element(){const classes=new Set();return {dataset:{},value:'',textContent:'',innerHTML:'',hidden:false,disabled:false,children:[{},{},{}],classList:{toggle(name,on){on?classes.add(name):classes.delete(name);},contains:name=>classes.has(name)},attributes:{},open:false,showModal(){this.open=true;},close(){this.open=false;},setAttribute(key,value){this.attributes[key]=value;},addEventListener(){},append(){},insertBefore(){},closest(){return element();}};}
function ui(api){ function ui(api){
const nodes=new Map(),tabs=['inbox','sent','queue','all'].map(folder=>{const e=element();e.dataset.wlfolder=folder;return e;});tabs[0].classList.toggle('active',true); const nodes=new Map(),tabs=['inbox','sent','queue','all'].map(folder=>{const e=element();e.dataset.wlfolder=folder;return e;});tabs[0].classList.toggle('active',true);
const $=selector=>{if(!nodes.has(selector))nodes.set(selector,element());return nodes.get(selector);}; const $=selector=>{if(!nodes.has(selector))nodes.set(selector,element());return nodes.get(selector);};
const context=vm.createContext({$, $$:selector=>selector==='[data-wlfolder]'?tabs:[],document:{body:element(),createElement:()=>element()},window:{},station:{call:'N0TEST'},csrf:'fixture',navigate(){},setInterval(){},setTimeout(){},openCompose(){},readMessage(){},esc:v=>String(v??''),mailTimezone:()=> 'UTC',logTime:v=>v,mailRow:m=>'#'+m.id,api}); const context=vm.createContext({$, $$:selector=>selector==='[data-wlfolder]'?tabs:[],document:{body:element(),createElement:()=>element()},window:{},deletedMessageIds:new Set(),allMessages:[],selected:null,loadGeneration:0,AbortSignal,renderMessages(){},loadMessages:async()=>{},loadDashboard(){},toast(){},station:{call:'N0TEST'},csrf:'fixture',navigate(){},setInterval(){},setTimeout(){},openCompose(){},readMessage(){},esc:v=>String(v??''),mailTimezone:()=> 'UTC',logTime:v=>v,mailRow:m=>'#'+m.id,api});
vm.runInContext(source,context);return {context,tabs,$,run:code=>vm.runInContext(code,context)}; vm.runInContext(source,context);return {context,tabs,$,run:code=>vm.runInContext(code,context)};
} }
const deferred=()=>{let resolve;const promise=new Promise(r=>resolve=r);return {promise,resolve};}; const deferred=()=>{let resolve;const promise=new Promise(r=>resolve=r);return {promise,resolve};};
@@ -24,3 +24,20 @@ test('a forced post-save refresh waits for an existing poll, discards its stale
test('simultaneous forced refreshes share the new request and cannot restore a deleted message',async()=>{ test('simultaneous forced refreshes share the new request and cannot restore a deleted message',async()=>{
const pending=[],view=ui(()=>{const d=deferred();pending.push(d);return d.promise;});const old=view.run('wlLoad()'),fresh=view.run('wlLoad(true)'),other=view.run('wlLoad(true)');pending[0].resolve(data([{id:7,folder:'inbox'}]));await old;await new Promise(setImmediate);assert.equal(pending.length,2);pending[1].resolve(data([]));await Promise.all([fresh,other]);assert.equal(view.run('wlData.messages.length'),0);assert.equal(view.run('wlLoadTask'),null); const pending=[],view=ui(()=>{const d=deferred();pending.push(d);return d.promise;});const old=view.run('wlLoad()'),fresh=view.run('wlLoad(true)'),other=view.run('wlLoad(true)');pending[0].resolve(data([{id:7,folder:'inbox'}]));await old;await new Promise(setImmediate);assert.equal(pending.length,2);pending[1].resolve(data([]));await Promise.all([fresh,other]);assert.equal(view.run('wlData.messages.length'),0);assert.equal(view.run('wlLoadTask'),null);
}); });
test('delete confirmation closes on success without waiting for list refreshes, and removes the row',async()=>{
const request=deferred();let deletes=0;const view=ui(url=>{if(url.includes('/delete')){deletes++;return request.promise;}return Promise.resolve(data([]));});
view.run('allMessages=[{id:7},{id:8}];selected=7;askDelete(7,"Test");');const action=view.$('#delete-confirm').onclick();assert.equal(view.run('deleteDialog.open'),true);assert.equal(view.$('#delete-confirm').disabled,true);
await view.$('#delete-confirm').onclick();assert.equal(deletes,1);request.resolve({ok:true});await action;
assert.equal(view.run('deleteDialog.open'),false);assert.equal(view.run('deletedMessageIds.has(7)'),true);assert.equal(view.run('allMessages.some(m=>m.id===7)'),false);assert.equal(view.run('selected'),null);assert.equal(view.$('#delete-confirm').disabled,false);
});
test('delete errors remain visible inside the dialog and keep the message and retry controls',async()=>{
const view=ui(async()=>{throw Error('BPQ did not confirm deletion');});view.run('allMessages=[{id:7}];askDelete(7,"Test");');await view.$('#delete-confirm').onclick();
assert.equal(view.run('deleteDialog.open'),true);assert.equal(view.$('#delete-error').hidden,false);assert.equal(view.$('#delete-error').textContent,'BPQ did not confirm deletion');assert.equal(view.run('allMessages.length'),1);assert.equal(view.run('deletedMessageIds.has(7)'),false);assert.equal(view.$('#delete-confirm').disabled,false);assert.equal(view.$('#delete-cancel').disabled,false);
});
test('late Winlink list snapshots cannot resurrect a confirmed deleted message',async()=>{
const view=ui(async()=>data([{id:7,folder:'inbox',subject:'Deleted'}]));view.run('deletedMessageIds.add(7)');await view.run('wlLoad()');assert.equal(view.run('wlData.messages.length'),0);
});