Reconstruct 7plus multipart attachments with CRC checks and image previews

This commit is contained in:
alberto committed 2026-10-16 13:19:23 +02:00
1 parent bcc3cd7a19
commit 94649dde33
6 files changed
+116 -4

No files matched your search

+9 -1
View File
@@ -60,7 +60,7 @@ BBS, chat, monitor e Winlink vengono abilitati in base alle applicazioni e alle
## Funzioni e dati
Dashboard scura, schermo intero, stato modem, chiamante/chiamato quando esposti, CPU di sistema, rotte NET/ROM e attività forwarding. BBS e Winlink hanno elenco sopra e lettura sotto, ricerca, composizione, risposta, cancellazione e allegati B2. Anteprime immagini, PDF e testo; HTML/SVG mostrati come testo. Messaggi 7plus scaricabili senza ricostruzione automatica.
Dashboard scura, schermo intero, stato modem, chiamante/chiamato quando esposti, CPU di sistema, rotte NET/ROM e attività forwarding. BBS e Winlink hanno elenco sopra e lettura sotto, ricerca, composizione, risposta, cancellazione e allegati B2. Anteprime immagini, PDF e testo; HTML/SVG mostrati come testo. I messaggi 7plus multipart vengono ricostruiti automaticamente quando tutte le parti sono disponibili e i controlli CRC sono validi.
Chat nativa con sessione condivisa dell'account sysop selezionato, utenti, stanze, collegamenti e messaggi privati; fino a 300 eventi in memoria. Monitor BPQTermTCP con filtri e download TXT; fino a 1000 frame in memoria. Disconnessione dopo due minuti senza polling.
@@ -90,3 +90,11 @@ Punti e tracce sono cliccabili, con nominativo, ultimo collegamento nel periodo,
Il diario espone eventi strutturati, non i log grezzi: password, challenge CMS, contenuto delle email e conversazioni chat non sono restituiti dall'API.
Il tipo di collegamento viene ricostruito anche dai comandi CONNECT con porta numerata e dagli accessi accettati nei log Telnet (orari locali Windows, convertiti in UTC). La correlazione usa nominativo e orario entro 20 secondi ed è indicata nei dettagli. Gli accessi locali sono distinti come Locale / Telnet. Se i log storici non archiviano il mezzo di ingresso, il diario mostra Nodo BPQ oppure Gateway Winlink e spiega il limite nei dettagli; non presume un collegamento radio o Internet. Sulla mappa tali mezzi sono distinti dal colore delle tracce radio e di rete.
## Immagini multipart 7plus
Il lettore individua i blocchi 7plus nei file .mes originali, preservando i byte a 8 bit, e raggruppa le parti per mittente, nome, dimensione, numero di parti, dimensione del blocco e timestamp 7plus. Non usa soltanto il titolo del bollettino: file diversi con lo stesso nome non vengono uniti automaticamente. La decodifica JavaScript verifica CRC primario, CRC secondario, sequenza delle righe, intestazioni e chiusure. Il riferimento di interoperabilità è il formato 7PLUS di Axel Bauda DG1BBQ ([sorgenti originali 2.25](https://ponce.cc/slackware/sources/repo/7pl225sr.zip)); non viene eseguito o distribuito un decoder esterno.
Aprendo una qualsiasi parte completa, il file ricostruito appare fra gli allegati, con anteprima e download; le immagini vengono mostrate direttamente nel lettore e il testo codificato resta espandibile. Sono elencati i messaggi che compongono il gruppo. Parti mancanti o danneggiate bloccano il download del risultato e vengono indicate. Copie valide della stessa parte possono completare righe mancanti; righe discordanti non vengono accettate. Non è implementata la riparazione tramite file COR/ERR.
Sono considerate soltanto le parti attualmente visibili nella BBS. Nessun messaggio viene modificato, scritto o cancellato; i risultati sono conservati in memoria (cache fino a 64 MB). Limite file ricostruito 32 MB, fino a 255 parti, scansione di messaggi fino a 2 MB ciascuno. Il download usa gli stessi controlli di sessione e autorizzazione degli altri allegati.
+1 -1
View File
@@ -2,6 +2,6 @@ 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();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)}</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){const box=document.createElement('div');box.className='encoded-attachment';box.innerHTML=`<b>7plus · ${esc(data.encoded.name)}</b><p>Parte ${data.encoded.part}/${data.encoded.total}. L’anteprima dell’immagine richiede il file ricostruito dalle parti complete.</p><a class="text-button" href="/api/messages/${id}/source" download>Scarica testo originale della parte ↓</a>`;section.append(box);}}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();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>`;}}
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'));};
+3
View File
@@ -79,3 +79,6 @@ body:has(#chat:not([hidden])) .topbar{height:64px}
.arrival-toast>div{min-width:0;flex:1}.arrival-toast strong{font-size:16px;line-height:1.4}.arrival-toast small{font-size:14px;line-height:1.55;margin-top:6px;overflow-wrap:anywhere}
.arrival-toast>button{width:32px;height:32px;min-width:32px;font-size:24px;align-self:flex-start}
@media(max-width:600px){.notification-stack{right:16px;bottom:16px}.arrival-toast{padding:16px;gap:12px}.arrival-toast strong{font-size:15px}.arrival-toast small{font-size:13px}}
.sevenplus-inline{white-space:normal;text-align:center;padding:16px;border:1px solid #38546b;border-radius:12px;background:#102335;margin-bottom:14px}.sevenplus-inline img{display:block;max-width:100%;width:auto;max-height:280px;object-fit:contain;margin:auto;cursor:zoom-in}.sevenplus-inline p{font-size:11px;color:#97b5cc;margin:12px 0 0}.sevenplus-original>summary{cursor:pointer;color:#88a8c4;font-size:11px;white-space:normal;padding:10px 0}.sevenplus-parts{display:flex;flex-wrap:wrap;gap:5px;margin:10px 0}.sevenplus-parts button{font-size:10px;padding:4px 7px}
.reader:has(.sevenplus-inline){display:block;overflow:auto}.reader:has(.sevenplus-inline) .reader-body{overflow:visible;max-height:none}.reader:has(.sevenplus-inline) .message-attachments{max-height:none;overflow:visible}
+4 -2
View File
@@ -1,5 +1,6 @@
import http from 'node:http';
import {Journal} from './journal.mjs';
import {SevenPlus} from './sevenplus.mjs';
import {loadConfig,parseConfig,publicConfig,ownCall} from './config.mjs';
import {readFile, stat} from 'node:fs/promises';
import path from 'node:path';
@@ -18,6 +19,7 @@ const dir=path.dirname(fileURLToPath(import.meta.url));
const config=await loadConfig();
const root=config.root;
const journal=new Journal(config,dir);
const sevenPlus=new SevenPlus(root);
const upstream='http://127.0.0.1:'+config.httpPort;
const sessions=new Map(), attempts=new Map();
const port=config.port;
@@ -41,7 +43,7 @@ async function bpqRequest(url, options={}) {
return new Promise((resolve,reject)=>{const request=http.request(upstream+url,{method:options.method||'GET',headers,agent:false},response=>{let chunks=[];response.on('data',c=>chunks.push(c));response.on('end',()=>{if(response.statusCode!==200)return reject(new Error('BPQ non risponde ('+response.statusCode+')'));resolve(Buffer.concat(chunks).toString('utf8'))});response.on('error',reject)});request.setTimeout(10000,()=>request.destroy(new Error('Timeout BPQ')));request.on('error',reject);if(payload)request.write(payload);request.end()});
}
async function mailContext(){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};}
async function messages(){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);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;}for(const m of list)Object.assign(m,await messageTimes(m.id));return list;}
async function messages(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);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;}if(includeTimes)for(const m of list)Object.assign(m,await messageTimes(m.id));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 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()||'{}');}
@@ -69,7 +71,7 @@ async function messageFields(id){let cached=metadataCache.get(id);if(cached&&Dat
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,direction:mailDirection(full,config.sysop.call),folder:mailFolder(full,config.sysop.call)});}}return out;}
async function winlink(){const list=await mailMetadata(await messages());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{}return {messages:list,sync,account:config.sysop.call.replace(/-\d+$/,'')+'@winlink.org',requestedAt:lastCmsRequest||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);if((await messages()).some(m=>m.id===id))throw new Error('BPQ non ha confermato la cancellazione');return {ok:true};}
async function attachedMessage(id){const item=(await messages()).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 encoded=item.subject.match(/^7\+\s+(.+?)\s+(\d+)\/(\d+)$/i);return {item,bytes,files,encoded:encoded?{name:safeName(encoded[1]),part:Number(encoded[2]),total:Number(encoded[3])}: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)};}
async function sendMessage(data){
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||!text||Buffer.byteLength(text)>32000||!['P','B'].includes(type))throw new Error('Controlla destinatario, oggetto (max 80 caratteri) e testo (max 32 KB)');
+88
View File
@@ -0,0 +1,88 @@
// 7plus interoperability: radix-216, 31-bit words and per-line CRC checks.
// Format reference: 7PLUS 2.25 by Axel Bauda DG1BBQ (original C sources).
// This module never executes attachments or writes decoded files to the BBS.
import {readFile,stat} from 'node:fs/promises';
import path from 'node:path';
import {createHash} from 'node:crypto';
import {safeName,mimeOf} from './attachments.mjs';
const alphabet=[];
for(const [start,end]of [[0x21,0x29],[0x2b,0x7e],[0x80,0x90],[0x92,0x92],[0x94,0xfc]])for(let b=start;b<=end;b++)alphabet.push(b);
const digits=new Int16Array(256).fill(-1);alphabet.forEach((b,i)=>digits[b]=i);
const table=Array.from({length:256},(_,n)=>{let v=n<<8;for(let bit=0;bit<8;bit++)v=((v<<1)^((v&0x8000)?0x1021:0))&0xffff;return v;});
function crc(bytes){let value=0;for(const byte of bytes)value=table[value>>>8]^(((value&255)<<8)|byte);return value;}
function digit(byte){const n=digits[byte];if(n<0||n===undefined)throw new Error('Carattere 7plus non valido');return n;}
function miniValid(line){const at=line.indexOf(Buffer.from([0xb0,0xb1]));return at>=0&&line.length>at+4&&crc(line.subarray(0,at+4))%216===digits[line[at+4]];}
function secondValid(line){return line.length===69&&(crc(Buffer.from(line.subarray(0,67)).reverse())&0x7fff)===digit(line[67])+216*digit(line[68]);}
const digest=bytes=>createHash('sha256').update(bytes).digest('hex');
export function decodeSevenLine(line){
if(line.length!==69)throw new Error('Riga 7plus incompleta (attesi 69 byte)');
const sequence=digit(line[64])+216*digit(line[65])+216*216*digit(line[66]);
if((crc(line.subarray(0,64))&0x3fff)!==(sequence&0x3fff)||!secondValid(line))throw new Error('Controllo CRC della riga non valido');
const out=Buffer.alloc(62);
for(let block=0;block<2;block++){
let bits=0n;for(let word=0;word<8;word++){const at=(block*8+word)*4;let value=0;for(let j=3;j>=0;j--)value=value*216+digit(line[at+j]);if(value>0x7fffffff)throw new Error('Parola 7plus fuori intervallo');bits=(bits<<31n)|BigInt(value);}
for(let i=30;i>=0;i--){out[block*31+i]=Number(bits&255n);bits>>=8n;}
}
return {number:sequence>>>14,data:out};
}
export function scanSevenPlus(bytes,id,sender=''){
const lines=bytes.toString('latin1').split(/\r\n|\n|\r/),blocks=[];
const from=lines.find(l=>/^From:\s*/i.test(l))?.replace(/^From:\s*/i,'').trim().toUpperCase()||String(sender).toUpperCase();
for(let i=0;i<lines.length;i++){
const header=lines[i],m=header.match(/^ go_7\+\.\s+(\d+) of (\d+) (\S+) (\d+) ([A-F0-9]+) ([A-F0-9]+) \(7PLUS v([^)]*)\)/i);if(!m)continue;
const part=Number(m[1]),total=Number(m[2]),name=safeName(m[3]),size=Number(m[4]),blockLines=parseInt(m[6],16),body=[];let footer=null;
for(i++;i<lines.length;i++){if(/^ stop_7\+\./i.test(lines[i])){footer=lines[i];break;}body.push(Buffer.from(lines[i],'latin1'));}
const stamp=footer?.match(/\[([A-F0-9]{1,8})\]/i)?.[1]?.toUpperCase().padStart(8,'0')||null;
let issue=null;
if(name!==m[3]||!part||total<1||total>255||part>total||size<1||size>32*1024*1024||blockLines<1||blockLines>512||Math.ceil(Math.ceil(size/62)/blockLines)!==total)issue='Metadati 7plus non validi';
if(!miniValid(Buffer.from(header,'latin1')))issue='CRC dell’intestazione non valido';
if(!footer||!stamp||!miniValid(Buffer.from(footer,'latin1')))issue='Fine parte mancante o CRC della chiusura non valido';
const key=digest(Buffer.from([from,name.toUpperCase(),size,total,blockLines,stamp||''].join('|')));
const footName=footer?.match(/^ stop_7\+\.\s+\(([^)]+)\)/i)?.[1]?.toUpperCase();const stem=name.replace(/\.[^.]+$/,'').toUpperCase();const expectedFoot=total===1?stem+'.7PL':stem+'.P'+part.toString(16).toUpperCase().padStart(2,'0')+'/'+total.toString(16).toUpperCase().padStart(2,'0');if(footName!==expectedFoot)issue='Chiusura della parte discordante con l’intestazione';
const valid=new Map();let bad=0;
if(!issue)for(const line of body){if(!line.length)continue;try{const decoded=decodeSevenLine(line);const expected=Math.min(blockLines,Math.ceil(size/62)-(part-1)*blockLines);if(decoded.number>=expected)throw new Error('Numero riga fuori parte');const prior=valid.get(decoded.number);if(prior&&!prior.equals(decoded.data)){issue='Righe duplicate discordanti';throw new Error(issue);}valid.set(decoded.number,decoded.data);}catch{bad++;}}
blocks.push({id,from,name,part,total,size,blockLines,stamp,key,issue,valid,bad,hash:digest(Buffer.from(header+'\n'+body.map(b=>b.toString('latin1')).join('\n')+'\n'+footer,'latin1'))});
}
return blocks;
}
export function assembleSevenPlus(blocks){
if(!blocks.length)return null;const first=blocks[0],group=blocks.filter(b=>b.key===first.key),parts=new Map();for(const b of group){if(!parts.has(b.part))parts.set(b.part,[]);parts.get(b.part).push(b);}
const metadata={name:first.name,part:first.part,total:first.total,size:first.size,availableParts:[...parts.keys()].sort((a,b)=>a-b),missingParts:[],damagedParts:[],messageIds:[...new Set(group.map(b=>b.id))].sort((a,b)=>a-b),state:'incomplete',issues:[]};
if(first.total<1||first.total>255||first.part<1||first.part>first.total||first.blockLines<1||first.blockLines>512||first.size<1||first.size>32*1024*1024||Math.ceil(Math.ceil(first.size/62)/first.blockLines)!==first.total){metadata.state='damaged';metadata.issues.push('Metadati 7plus fuori limite');return {metadata,file:null};}
const pieces=[];
for(let part=1;part<=first.total;part++){
const candidates=parts.get(part);if(!candidates){metadata.missingParts.push(part);continue;}
const rows=new Map();let conflict=false;
for(const block of candidates.filter(b=>!b.issue))for(const [number,bytes]of block.valid){if(rows.has(number)&&!rows.get(number).equals(bytes))conflict=true;else rows.set(number,bytes);}
const count=Math.min(first.blockLines,Math.ceil(first.size/62)-(part-1)*first.blockLines);let missing=false;
for(let n=0;n<count;n++){if(!rows.has(n)){missing=true;break;}}
if(missing||conflict){metadata.damagedParts.push(part);continue;}
for(let n=0;n<count;n++)pieces.push(rows.get(n));
}
metadata.issues=[...new Set(group.map(b=>b.issue).filter(Boolean))];
if(metadata.missingParts.length||metadata.damagedParts.length){metadata.state=metadata.missingParts.length?'incomplete':'damaged';return {metadata,file:null};}
const data=Buffer.concat(pieces).subarray(0,first.size),mime=mimeOf(data,first.name);
if(data.length!==first.size||(/\.jpe?g$/i.test(first.name)&&(mime!=='image/jpeg'||data[data.length-2]!==255||data[data.length-1]!==217))){metadata.state='damaged';metadata.issues.push('Il file ricostruito non corrisponde al formato o alla dimensione dichiarata');return {metadata,file:null};}
metadata.state='complete';metadata.sha256=digest(data);
return {metadata,file:{name:first.name,size:data.length,mime,data,reconstructed:true,parts:first.total}};
}
export class SevenPlus{
constructor(root){this.root=root;this.scanned=new Map();this.cache=new Map();}
async forMessage(id,list){
const blocks=[];
for(const item of list){
const file=path.join(this.root,'BPQMailChat','Mail','m_'+String(item.id).padStart(6,'0')+'.mes');
try{const info=await stat(file);if(info.size>2*1024*1024)continue;const key=info.size+':'+info.mtimeMs;let cached=this.scanned.get(item.id);if(cached?.key!==key){cached={key,blocks:scanSevenPlus(await readFile(file),item.id,item.from)};this.scanned.set(item.id,cached);}blocks.push(...cached.blocks);}catch{}
}
const visible=new Set(list.map(m=>m.id));for(const key of this.scanned.keys())if(!visible.has(key))this.scanned.delete(key);
const requested=blocks.find(b=>b.id===Number(id));if(!requested)return null;
const group=blocks.filter(b=>b.key===requested.key);const signature=digest(Buffer.from(group.map(b=>b.hash+':'+b.id).join('|')));let result=this.cache.get(signature);
if(!result){result=assembleSevenPlus([requested,...group.filter(b=>b!==requested)]);this.cache.set(signature,result);let total=0;for(const r of this.cache.values())total+=r.file?.size||0;while(this.cache.size>16||total>64*1024*1024){const key=this.cache.keys().next().value;total-=this.cache.get(key).file?.size||0;this.cache.delete(key);}}
return {...result,metadata:{...result.metadata,part:requested.part}};
}
}
+11
View File
@@ -79,3 +79,14 @@ test('journal saves locators only for observed stations and validates input',asy
test('journal identifies Telnet access without exposing credentials or IP addresses',async()=>{const {parseTelnetLog,classifyTransport}=await import('./journal.mjs');const rows=parseTelnetLog('16/10/2026 12:00:00 1 127.0.0.1 Incoming Connect on Port 8100\n16/10/2026 12:00:01 1 127.0.0.1 Call Accepted Callsign=N0TEST\n16/10/2026 12:00:02 1 127.0.0.1 password=secret-fixture','Telnet_261016.log');assert.equal(rows.length,1);assert.equal(rows[0].local,true);assert.equal(rows[0].port,8100);assert.equal(JSON.stringify(rows).includes('secret-fixture'),false);assert.equal(JSON.stringify(rows).includes('127.0.0.1'),false);const s=classifyTransport({call:'N0TEST-12',startedAt:rows[0].at,service:'Chat',transport:'Unknown',sources:[]},{ports:[]},rows);assert.equal(s.transport,'Local');assert.ok(s.sources.includes('Telnet_261016.log'));});
test('journal classifies explicit BPQ ports and keeps historical missing ports honest',async()=>{const {classifyTransport}=await import('./journal.mjs');const config={ports:[{id:1,driver:'SCSPACTOR'},{id:2,driver:'TELNET'},{id:4,driver:'BPQAXIP'}]};for(const [port,expected]of [[1,'Radio'],[2,'Internet'],[4,'NET/ROM']])assert.equal(classifyTransport({port,transport:'Unknown',sources:[]},config).transport,expected);const cms=classifyTransport({call:'N2TEST',service:'Winlink',transport:'Unknown',sources:[]},config);assert.equal(cms.transport,'CMS');assert.match(cms.transportEvidence,/non è archiviato/);const bbs=classifyTransport({call:'N2TEST',service:'BBS',transport:'Unknown',sources:[]},config);assert.equal(bbs.transport,'BPQ');assert.match(bbs.transportEvidence,/porta di ingresso non è archiviata/);});
test('journal parses CONNECT with a numbered port',async()=>{const {parseBbsLog,classifyTransport}=await import('./journal.mjs');const s=parseBbsLog('261016 12:00:00 |N2TEST Connecting to BBS N2TEST\n261016 12:00:01 >N2TEST C 4 N2TEST-11\n261016 12:00:20 |N2TEST N2TEST Disconnected')[0];assert.equal(s.port,4);assert.equal(classifyTransport(s,{ports:[{id:4,driver:'BPQAXIP'}]}).transport,'NET/ROM');});
// Small protocol fixture: standard JFIF header bytes, not a stored BBS image.
const sevenLineHex='7aaef5f9aec026218ba6d09e5830c53c52502521ce9eb22729adfa2be17d7029352324265cc8ec23b66436239e315058cdfa2158bdb8418ea16c4f72b2c6d046b84921987b';
const sevenDecodedHex='ffd8ffe000104a46494600010101006000600000ffdb00430006040506050406060506070706080a100a0a09090a140e0f0c1017141818171416161a1d25';
const sevenHeaders=['20676f5f372b2e20303031206f6620303032205041594c4f41442e42494e2030303030313030203030343020303031202837504c55532076322e31292020b0b1b2db4d9b97','20676f5f372b2e20303032206f6620303032205041594c4f41442e42494e2030303030313030203030343020303031202837504c55532076322e31292020b0b1b2dbb04996'];
const sevenFooters=['2073746f705f372b2e20285041594c4f41442e5030312f303229205b31323334353637385d20202020202020202020202020202020202020202020202020b0b1b2db588db4','2073746f705f372b2e20285041594c4f41442e5030322f303229205b31323334353637385d20202020202020202020202020202020202020202020202020b0b1b2dbdd8925'];
function sevenFixture(part,sender='N0TEST'){return Buffer.concat([Buffer.from('From: '+sender+'\r\n\r\n'),Buffer.from(sevenHeaders[part-1],'hex'),Buffer.from('\r\n'),Buffer.from(sevenLineHex,'hex'),Buffer.from('\r\n'),Buffer.from(sevenFooters[part-1],'hex'),Buffer.from('\r\n')]);}
test('7plus decodes a known binary line and verifies both CRC fields',async()=>{const {decodeSevenLine}=await import('./sevenplus.mjs');const line=Buffer.from(sevenLineHex,'hex'),result=decodeSevenLine(line);assert.equal(result.number,0);assert.equal(result.data.toString('hex'),sevenDecodedHex);for(const at of [0,64,67]){const damaged=Buffer.from(line);damaged[at]^=1;assert.throws(()=>decodeSevenLine(damaged));}assert.throws(()=>decodeSevenLine(line.subarray(0,68)));});
test('7plus combines out-of-order parts and refuses incomplete or damaged groups',async()=>{const {scanSevenPlus,assembleSevenPlus}=await import('./sevenplus.mjs');const first=scanSevenPlus(sevenFixture(1),1),second=scanSevenPlus(sevenFixture(2),2);assert.equal(first[0].issue,null);assert.equal(second[0].issue,null);const incomplete=assembleSevenPlus(first);assert.equal(incomplete.metadata.state,'incomplete');assert.deepEqual(incomplete.metadata.missingParts,[2]);assert.equal(incomplete.file,null);const done=assembleSevenPlus([...second,...first]);assert.equal(done.metadata.state,'complete');assert.equal(done.file.size,100);assert.deepEqual(done.file.data,Buffer.concat([Buffer.from(sevenDecodedHex,'hex'),Buffer.from(sevenDecodedHex,'hex')]).subarray(0,100));const damaged=sevenFixture(2);damaged[damaged.indexOf(Buffer.from(sevenLineHex,'hex'))]^=1;const failed=assembleSevenPlus([...first,...scanSevenPlus(damaged,2)]);assert.equal(failed.metadata.state,'damaged');assert.deepEqual(failed.metadata.damagedParts,[2]);assert.equal(failed.file,null);});
test('7plus isolates senders and rejects unsafe metadata before allocating data',async()=>{const {scanSevenPlus,assembleSevenPlus}=await import('./sevenplus.mjs');const a=scanSevenPlus(sevenFixture(1,'N0TEST'),1),b=scanSevenPlus(sevenFixture(2,'N1OTHER'),2);assert.notEqual(a[0].key,b[0].key);assert.equal(assembleSevenPlus([...a,...b]).file,null);const bad={...a[0],total:999999999,size:1e15};assert.equal(assembleSevenPlus([bad]).metadata.state,'damaged');const damagedHeader=sevenFixture(1);damagedHeader[damagedHeader.indexOf(Buffer.from('PAYLOAD.BIN'))]^=1;assert.ok(scanSevenPlus(damagedHeader,1)[0].issue);});
test('7plus includes only currently visible messages and invalidates a removed part',async()=>{const {SevenPlus}=await import('./sevenplus.mjs');const fs=await import('node:fs/promises'),path=await import('node:path'),os=await import('node:os');const tmp=await fs.mkdtemp(path.join(os.tmpdir(),'bpq-sevenplus-test-'));try{await fs.mkdir(path.join(tmp,'BPQMailChat','Mail'),{recursive:true});await fs.writeFile(path.join(tmp,'BPQMailChat','Mail','m_000001.mes'),sevenFixture(1));await fs.writeFile(path.join(tmp,'BPQMailChat','Mail','m_000002.mes'),sevenFixture(2));const codec=new SevenPlus(tmp);const first=await codec.forMessage(1,[{id:1}]);assert.equal(first.file,null);const full=await codec.forMessage(1,[{id:1},{id:2}]);assert.equal(full.file.size,100);const hidden=await codec.forMessage(1,[{id:1}]);assert.equal(hidden.file,null);assert.equal(hidden.metadata.state,'incomplete');}finally{await fs.rm(tmp,{recursive:true,force:true})}});