diff --git a/README.md b/README.md
index e9ed02b..cac0f3d 100644
--- a/README.md
+++ b/README.md
@@ -8,6 +8,12 @@ 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.
+## 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.
+
+In **New email**, use **Attach files** or drop files into the attachment panel. Review filenames, sizes and image thumbnails; remove files before saving. The Console accepts up to 10 files and 64 KiB total per outgoing email, with a combined message text/file limit of 80 KiB and the existing 32 KB body limit. These Console upload limits leave room for multipart headers within the native BPQ HTTP input buffer; BPQ, the receiving gateway and radio conditions may impose further limits. Small files are preferable over radio. Files stay in the browser until the message is saved and then use BPQ’s native WebMail attachment upload and normal Winlink queue, over Internet or radio. The Console verifies that BPQ stored the same filenames and file bytes before confirming success. If it reports a saved message with mismatched attachments, check the queue before retrying.
+
## Telnet login compatibility
Terminal and Chat read `LOGINPROMPT` and `PASSWORDPROMPT` from the Telnet port in `BPQ32.cfg`. Standard `Username:`, `Login:`, `User:` and `Password:` prompts also work. `PASSWORD` is not the prompt setting. Custom CTEXT banners do not need the word Welcome or a node prompt; both `ALIAS:CALL>` and `ALIAS:CALL}` work. After the password, the clients wait for 400 ms of quiet after non-empty banner text; a repeated login/password prompt or explicit denial rejects the login. Password echoes are removed before displaying the terminal banner, and Chat discards the Telnet banner before sending `CHAT`. A server that sends no text at all after the password times out instead of reporting an unconfirmed login as successful. Restart BPQ Console after changing prompt settings.
diff --git a/attachments.mjs b/attachments.mjs
index ee215a1..f8bf876 100644
--- a/attachments.mjs
+++ b/attachments.mjs
@@ -1,4 +1,5 @@
import path from 'node:path';
+export function attachmentSummary(bytes){const end=bytes.indexOf('\r\n\r\n');if(end<0||end>65536)return {attachmentCount:0,attachmentBytes:0};const header=bytes.subarray(0,end).toString('utf8');if(!/^MID:/mi.test(header)||!/^Body:\s*\d+\s*$/mi.test(header))return {attachmentCount:0,attachmentBytes:0};const files=[...header.matchAll(/^File:\s*(\d+)\s+[^\r\n]+\r?$/gmi)];return {attachmentCount:files.length,attachmentBytes:files.reduce((sum,f)=>sum+Number(f[1]),0)};}
export function safeName(name){return path.win32.basename(String(name).replaceAll('/','\\')).replace(/[\x00-\x1f\x7f]/g,'').slice(0,200)||'allegato.bin';}
export function mimeOf(bytes,name){if(bytes.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10])))return 'image/png';if(bytes[0]===255&&bytes[1]===216&&bytes[2]===255)return 'image/jpeg';if(/^GIF8[79]a$/.test(bytes.subarray(0,6).toString('ascii')))return 'image/gif';if(bytes.subarray(0,4).toString()==='RIFF'&&bytes.subarray(8,12).toString()==='WEBP')return 'image/webp';if(bytes.subarray(0,5).toString()==='%PDF-')return 'application/pdf';if(/\.(txt|csv|log|json|xml|html?|svg|md|7pl)$/i.test(name)&&!bytes.subarray(0,4096).includes(0))return 'text/plain';return 'application/octet-stream';}
export function b2Body(bytes){const end=bytes.indexOf('\r\n\r\n');if(end<0||end>65536)return null;const header=bytes.subarray(0,end).toString('utf8'),body=header.match(/^Body:\s*(\d+)\s*$/m);if(!body||!/^Mid:/mi.test(header))return null;const length=Number(body[1]);if(end+4+length>bytes.length)throw new Error('Corpo B2 incompleto');const data=bytes.subarray(end+4,end+4+length);try{return new TextDecoder('utf8',{fatal:true}).decode(data);}catch{return data.toString('latin1');}}
diff --git a/mail-upload.integration.test.mjs b/mail-upload.integration.test.mjs
new file mode 100644
index 0000000..8d6634e
--- /dev/null
+++ b/mail-upload.integration.test.mjs
@@ -0,0 +1,49 @@
+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 {parseAttachments,b2Body} from './attachments.mjs';
+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()=>{
+ 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 mail=path.join(root,'BPQMailChat','Mail');await fs.mkdir(mail,{recursive:true});
+ const server=http.createServer(async(req,res)=>{try{
+ if(req.url==='/Webmail'){res.end('Mail');return;}
+ if(req.url.startsWith('/WebMail/NewMsg')){res.end('Compose');return;}
+ if(req.url.startsWith('/WebMail/EMSave')){
+ nativePosts++;const chunks=[];for await(const chunk of req)chunks.push(chunk);
+ const form=await new Request('http://localhost/',{method:'POST',headers:{'Content-Type':req.headers['content-type']},body:Buffer.concat(chunks)}).formData();
+ assert.equal(form.get('To'),'RMS/ALICE@EXAMPLE.TEST');const files=await Promise.all(form.getAll('myFile[]').map(async f=>({name:f.name,data:Buffer.from(await f.arrayBuffer())})));assert.equal(files.length,2);
+ 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;
+ }
+ if(req.url.startsWith('/WebMail/WMALL')){res.end('Message List\r\n'+(nextId?' 1 17-Oct PN 100 '+['RMS','','N0TEST'].map(s=>s.padEnd(7)).join(' ')+' Attachment fixture\r\n':''));return;}
+ if(req.url==='/Mail/Status'){res.end('Messages');return;}
+ if(req.url.startsWith('/Mail/MsgDetails')){res.end(Object.entries({From:'N0TEST',To:'RMS',Title:'Attachment fixture',VIA:'ALICE@EXAMPLE.TEST',Sent:'17-Oct 12:00Z',RX:'17-Oct 12:00Z'}).map(([k,v])=>'').join(''));return;}
+ if(req.url.startsWith('/WebMail/WM?')){res.end('');return;}
+ res.end('BPQ Ports');
+ }catch(e){res.statusCode=500;res.end(e.message);}});
+ try{
+ await listen(server);const probe=net.createServer();await listen(probe);const port=probe.address().port;await new Promise(resolve=>probe.close(resolve));
+ await fs.writeFile(path.join(root,'BPQ32.cfg'),'NODECALL=N0TEST-7\nPORT\nDRIVER=TELNET\nHTTPPORT='+server.address().port+'\nCMS=1\nUSER=admin,fixture-secret,N0TEST,sysop\nENDPORT\nAPPLICATION 1,BBS,,N0TEST-11,MAIL\n');
+ await fs.writeFile(path.join(root,'BPQMailChat','BPQMail.cfg'),'BBSForwarding : {}\nBBSUsers : {}');
+ await fs.writeFile(path.join(dir,'package.json'),' {"type":"module"} ');await fs.writeFile(path.join(dir,'console.config.json'),JSON.stringify({bpqRoot:root,port}));
+ for(const name of await fs.readdir('.'))if(name.endsWith('.mjs')&&!name.includes('.test.')&&name!=='test.mjs')await fs.copyFile(name,path.join(dir,name));
+ 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']});
+ await Promise.race([once(child.stdout,'data'),once(child,'exit').then(()=>{throw Error('Fixture server failed');}),new Promise((_,reject)=>{const timer=setTimeout(()=>reject(Error('Fixture timeout')),8000);timer.unref();})]);
+ const base='http://127.0.0.1:'+port,headers={origin:base,'content-type':'application/json'};
+ const login=await fetch(base+'/api/login',{method:'POST',headers,body:JSON.stringify({user:'admin',password:'fixture-secret'})});const auth=await login.json();headers.cookie=login.headers.get('set-cookie').split(';')[0];headers['x-csrf-token']=auth.csrf;
+ const bytes=[Buffer.from([255,216,255,0,13,10,255]),Buffer.from('Città 📻')],form=new FormData();
+ for(const [key,value]of Object.entries({to:'RMS/alice@example.test',subject:'Attachment fixture',text:'Hello à',type:'P'}))form.set(key,value);
+ form.append('files',new Blob([bytes[0]]),'image.jpg');form.append('files',new Blob([bytes[1]]),'note.txt');delete headers['content-type'];
+ const created=await fetch(base+'/api/messages',{method:'POST',headers,body:form});assert.equal(created.status,201,await created.clone().text());assert.deepEqual(await created.json(),{id:1,attachmentCount:2});assert.equal(nativePosts,1);
+ assert.equal(b2Body(stored),'Hello à');assert.deepEqual(parseAttachments(stored).map(f=>f.data),bytes);
+ const files=await (await fetch(base+'/api/messages/1/attachments',{headers})).json();assert.equal(files.files.length,2);assert.equal(files.files[0].mime,'image/jpeg');assert.ok(!('data' in files.files[0]));
+ const download=await fetch(base+'/api/messages/1/attachments/0',{headers});assert.match(download.headers.get('content-disposition'),/^attachment/);assert.deepEqual(Buffer.from(await download.arrayBuffer()),bytes[0]);
+ const preview=await fetch(base+'/api/messages/1/attachments/0?preview=1',{headers});assert.equal(preview.headers.get('content-type'),'image/jpeg');
+ const text=await (await fetch(base+'/api/messages/1/attachments/1?text=1',{headers})).json();assert.equal(text.text,'Città 📻');
+ const reader=await (await fetch(base+'/api/messages/1',{headers})).json();assert.equal(reader.text,'Hello à');
+ const inbox=await (await fetch(base+'/api/winlink',{headers})).json();assert.equal(inbox.messages[0].attachmentCount,2);assert.equal(inbox.messages[0].folder,'queue');
+ 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/alice@example.test',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);
+ }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});}
+});
diff --git a/mail-upload.mjs b/mail-upload.mjs
new file mode 100644
index 0000000..6f13b38
--- /dev/null
+++ b/mail-upload.mjs
@@ -0,0 +1,33 @@
+import {safeName,mimeOf,parseAttachments} from './attachments.mjs';
+export const uploadLimits={files:10,bytes:64*1024,messageBytes:80*1024,requestBytes:96000};
+export async function readSubmission(req){
+ const chunks=[];let length=0;
+ for await(const chunk of req){length+=chunk.length;if(length>uploadLimits.requestBytes)throw Error('Allegati troppo grandi: massimo 64 KB complessivi');chunks.push(chunk);}
+ const bytes=Buffer.concat(chunks),contentType=req.headers['content-type']||'';
+ if(!/^multipart\/form-data\s*;/i.test(contentType)){
+ if(bytes.length>70000)throw Error('Messaggio troppo grande');
+ const data=JSON.parse(bytes.toString()||'{}');if(data.files||data.attachments)throw Error('Usa il caricamento file per gli allegati');return {...data,files:[]};
+ }
+ const form=await new Request('http://localhost/upload',{method:'POST',headers:{'Content-Type':contentType},body:bytes}).formData();
+ const data={},files=[];let total=0;
+ for(const [key,value]of form){
+ if(typeof value==='string'){if(!['to','subject','text','type'].includes(key)||key in data)throw Error('Campi del messaggio non validi');data[key]=value;continue;}
+ if(key!=='files')throw Error('Campo allegato non valido');
+ if(files.length>=uploadLimits.files)throw Error('Massimo 10 allegati per messaggio');
+ total+=value.size;if(total>uploadLimits.bytes)throw Error('Allegati troppo grandi: massimo 64 KB complessivi');
+ const name=safeName(value.name).replace(/[";]/g,'_'),buffer=Buffer.from(await value.arrayBuffer());
+ if(files.some(f=>f.name.toLowerCase()===name.toLowerCase()))throw Error('Nomi allegati duplicati: rinomina i file');
+ files.push({name,size:buffer.length,data:buffer,mime:mimeOf(buffer,name)});
+ }
+ return {...data,files};
+}
+export function outgoingForm({to,subject,text,type,files=[]}){
+ const form=new FormData();for(const [key,value]of Object.entries({To:to,Subj:subject,Type:type,BID:'',Msg:text.replace(/\r?\n/g,'\r\n'),Send:'Send'}))form.set(key,value);
+ for(const file of files)form.append('myFile[]',new Blob([file.data],{type:'application/octet-stream'}),file.name);
+ return form;
+}
+export function verifySavedAttachments(bytes,expected){
+ const actual=parseAttachments(bytes);
+ if(actual.length!==expected.length||expected.some((file,i)=>file.name!==actual[i].name||!file.data.equals(actual[i].data)))throw Error('BPQ ha salvato il messaggio ma gli allegati non corrispondono. Controlla la coda prima di riprovare.');
+ return actual.map(({data,...file})=>file);
+}
diff --git a/mail-upload.test.mjs b/mail-upload.test.mjs
new file mode 100644
index 0000000..98d91c8
--- /dev/null
+++ b/mail-upload.test.mjs
@@ -0,0 +1,31 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import {Readable} from 'node:stream';
+import {readSubmission,outgoingForm,verifySavedAttachments,uploadLimits} from './mail-upload.mjs';
+import {parseAttachments,b2Body,attachmentSummary} from './attachments.mjs';
+
+async function request(form){const r=new Request('http://localhost/messages',{method:'POST',body:form}),stream=Readable.from([Buffer.from(await r.arrayBuffer())]);stream.headers={'content-type':r.headers.get('content-type')};return stream;}
+function b2(body,files){return Buffer.concat([Buffer.from('MID: fixture\r\nBody: '+Buffer.byteLength(body)+'\r\n'+files.map(f=>'File: '+f.data.length+' '+f.name+'\r\n').join('')+'\r\n'+body+'\r\n'),...files.flatMap(f=>[f.data,Buffer.from('\r\n')])]);}
+test('multipart upload reaches native BPQ fields with byte-exact binary and UTF8 files',async()=>{
+ const files=[{name:'image.jpg',data:Buffer.from([255,216,255,0,13,10,255])},{name:'note.txt',data:Buffer.from('Città e radio 📻')}];
+ const form=new FormData();for(const [k,v]of Object.entries({to:'RMS/alice@example.test',subject:'Attachments',text:'Hello à',type:'P'}))form.set(k,v);for(const f of files)form.append('files',new Blob([f.data]),f.name);
+ const data=await readSubmission(await request(form));assert.equal(data.files.length,2);for(let i=0;i Nessun messaggio corrisponde ai filtri. ${esc(err.message)}Caricamento messaggio…
${esc(m.subject)}
Messaggio non disponibile
Allegato
Anteprima non disponibile. Puoi scaricare il file.
';$('#attachment-preview').replaceChildren(image);}else if(file.mime==='application/pdf'){try{await renderPdf(url+'?preview=1',generation)}catch{if(generation===attachmentGeneration)$('#attachment-preview').innerHTML='Anteprima PDF non disponibile. Puoi scaricare il file.
';}}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='Anteprima non disponibile per questo formato. Puoi scaricare il file.
';}} -async function showAttachments(id,reader){const section=document.createElement('section');section.className='message-attachments';section.innerHTML='Controllo allegati…';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=`${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.'}
${data.encoded.issues?.length?''+esc(data.encoded.issues.join(' · '))+'
':''}${data.encoded.messageIds?.length?'${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.'}
${data.encoded.issues?.length?''+esc(data.encoded.issues.join(' · '))+'
':''}${data.encoded.messageIds?.length?'Trascina qui i file oppure selezionali. Massimo 10 file e 64 KB complessivi. Via radio, i file piccoli riducono il tempo di collegamento.
'; + form.querySelector('.compose-help').before(panel); + const scrollBody=document.createElement('div');scrollBody.className='compose-scroll-body';const heading=form.querySelector('.dialog-heading'),footer=form.querySelector('footer'); + while(heading.nextSibling&&heading.nextSibling!==footer)scrollBody.append(heading.nextSibling);heading.after(scrollBody); + const input=panel.querySelector('input'),list=panel.querySelector('#compose-file-list');let files=[],sending=false; + const total=()=>files.reduce((sum,item)=>sum+item.file.size,0); + function render(){ + panel.hidden=!wlCompose;panel.querySelector('#compose-file-total').textContent=files.length+' / 10 · '+size(total())+' / 64 KB';panel.querySelector('#compose-file-add').disabled=sending||files.length>=10;input.disabled=sending; + list.innerHTML=files.map((item,i)=>'La tua stazione, in un unico pannello.
${esc(e.message)}
`}} $$('[data-wlfolder]').forEach(b=>b.onclick=()=>{wlFolder=b.dataset.wlfolder;$$('[data-wlfolder]').forEach(x=>x.classList.toggle('active',x===b));wlRender()});$('#wl-search').oninput=wlRender; function wlNew(data={}){wlCompose=true;openCompose(data);$('#compose-form').elements.type.value='P';$('#compose-form').elements.type.closest('label').hidden=true;$('#compose-form').elements.to.placeholder='Nominativo Winlink oppure nome@example.com';$('#compose .dialog-heading h2').textContent='Nuova email';} -$('#wl-compose').onclick=()=>wlNew();$('#compose').addEventListener('close',()=>{wlCompose=false;$('#compose-form').elements.type.closest('label').hidden=false;$('#compose .dialog-heading h2').textContent='Nuovo messaggio';$('#compose-form').elements.to.placeholder='Nominativo oppure indirizzo email';}); +const baseOpenCompose=openCompose;openCompose=function(data={}){window.bpqComposeAttachments?.reset();baseOpenCompose(data);}; +$('#wl-compose').onclick=()=>wlNew();$('#compose').addEventListener('close',()=>{wlCompose=false;window.bpqComposeAttachments?.reset();$('#compose-form').elements.type.closest('label').hidden=false;$('#compose .dialog-heading h2').textContent='Nuovo messaggio';$('#compose-form').elements.to.placeholder='Nominativo oppure indirizzo email';}); $('#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)}}; setInterval(()=>{if(csrf&&page==='winlink')wlLoad()},5000); diff --git a/server.mjs b/server.mjs index 145712a..a7e0c95 100644 --- a/server.mjs +++ b/server.mjs @@ -1,3 +1,4 @@ +import {readSubmission,outgoingForm,verifySavedAttachments,uploadLimits} from './mail-upload.mjs'; import {SyncOperations} from './sync-operations.mjs'; import {RadioControl} from './radio-control.mjs'; import {Terminal} from './terminal.mjs'; @@ -12,7 +13,7 @@ import {forwardingHistory} from './forwarding.mjs'; import {Forwarding} from './forwarding.mjs'; import {SevenPlus} from './sevenplus.mjs'; import {loadConfig,parseConfig,publicConfig,ownCall} from './config.mjs'; -import {readFile, stat} from 'node:fs/promises'; +import {readFile, stat,open} from 'node:fs/promises'; import path from 'node:path'; import {fileURLToPath} from 'node:url'; import {randomBytes,timingSafeEqual} from 'node:crypto'; @@ -23,7 +24,7 @@ import {VaraRate} from './vara-rate.mjs'; import {mailDirection,mailFolder,cmsStatus} from './model.mjs'; import os from 'node:os'; import {execFile} from 'node:child_process'; -import {parseAttachments,safeName,b2Body} from './attachments.mjs'; +import {parseAttachments,safeName,b2Body,attachmentSummary} from './attachments.mjs'; const dir=path.dirname(fileURLToPath(import.meta.url)); const config=await loadConfig(); @@ -51,7 +52,7 @@ async function bpqRequest(url, options={}) { // BPQ's legacy HTTP server is compatible with plain HTTP requests; modern // fetch headers can make its local-auth detection fall back to the signon page. let payload=options.body,headers={Connection:'close'}; - if(payload instanceof FormData){const encoded=new Request(upstream+url,{method:'POST',body:payload});headers['Content-Type']=encoded.headers.get('content-type');payload=Buffer.from(await encoded.arrayBuffer());} + if(payload instanceof FormData){const encoded=new Request(upstream+url,{method:'POST',body:payload});headers['Content-Type']=encoded.headers.get('content-type');payload=Buffer.from(await encoded.arrayBuffer());if(payload.length>96000)throw Error('Messaggio troppo grande per il server HTTP BPQ');} if(payload){payload=Buffer.from(payload);headers['Content-Length']=payload.length;} 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()}); } @@ -91,29 +92,36 @@ async function messageTimes(id){if(timestampCache.has(id))return timestampCache. const metadataCache=new Map();let metadataKey=null,metadataKeyAt=0; function messageFields(id){return metadataReads.run(id,()=>readMessageFields(id));} async function readMessageFields(id,retry=true){let cached=metadataCache.get(id);if(cached&&Date.now()-cached.at<60000)return cached.fields;if(!metadataKey||Date.now()-metadataKeyAt>600000){const status=await bpq('/Mail/Status');metadataKey=status.match(/href=\/Mail\/Msgs\?([^\s>]+)/)?.[1];metadataKeyAt=Date.now();}if(!metadataKey)throw new Error('Metadati BBS non disponibili');const html=await bpq('/Mail/MsgDetails?'+metadataKey,{method:'POST',body:String(id)});const fields={};for(const input of html.matchAll(/]*>/gi)){const name=input[0].match(/\bname=(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i),value=input[0].match(/\bvalue=(?:"([^"]*)"|'([^']*)'|([^\s>]*))/i);if(name)fields[name[1]??name[2]??name[3]]=decode(value?.[1]??value?.[2]??value?.[3]??'');}if(!('From' in fields)||!('Title' in fields)){metadataKey=null;metadataKeyAt=0;if(retry)return readMessageFields(id,false);throw Error('Metadati BBS non ancora disponibili');}metadataCache.set(id,{at:Date.now(),fields});return fields;} -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 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 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};} 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){ +let messageWriteQueue=Promise.resolve(); +function sendMessage(data){const write=messageWriteQueue.then(()=>writeMessage(data));messageWriteQueue=write.catch(()=>{});return write;} +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'); - 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)'); + 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)'); + const files=data.files||[];if(files.length&&(type!=='P'||!/^RMS[/:]/i.test(to)))throw Error('Gli allegati in uscita sono disponibili per le email Winlink'); + if(Buffer.byteLength(text.replace(/\r?\n/g,'\r\n'))+files.reduce((n,f)=>n+f.size,0)>uploadLimits.messageBytes)throw Error('Testo e allegati superano 80 KB complessivi'); const previous=new Set((await messages()).map(m=>m.id)); - const {key}=await mailContext();await bpq('/WebMail/NewMsg?'+key); - const form=new FormData();for(const [k,v]of Object.entries({To:to,Subj:subject,Type:type,BID:'',Msg:text.replace(/\r?\n/g,'\r\n'),Send:'Send'}))form.set(k,v); + // A separate native compose session prevents a reader from replacing its attachments. + const composePage=await bpq('/Webmail'),key=composePage.match(/WMB\?([^>\s]+)/)?.[1];if(!key)throw Error('WebMail BPQ non disponibile');await bpq('/WebMail/NewMsg?'+key); + const form=outgoingForm({to,subject,text,type,files}); const response=await bpq('/WebMail/EMSave?'+key,{method:'POST',body:form}); if(/alert\(/i.test(response)&&!/(sent|saved|created)/i.test(response))throw new Error(plain(response.match(/alert\(["']([^"']+)/)?.[1]||'BPQ ha rifiutato il messaggio')); // A successful write must be visible in BPQ's message list, not inferred from HTTP 200. mailReads.clear();const list=await messages();const expectedTo=/^RMS[/:]/.test(to)||/@[^@]*\./.test(to)?'RMS':to.split('@')[0];const created=list.find(m=>!previous.has(m.id)&&ownCall(m.from,config.sysop.call)&&m.subject===subject&&(m.to===expectedTo||m.to===to.split('@')[0])); if(!created)throw new Error('BPQ non ha confermato il salvataggio. Controlla la lista prima di riprovare.'); - return {id:created.id}; + if(files.length){const saved=await readFile(path.join(root,'BPQMailChat','Mail','m_'+String(created.id).padStart(6,'0')+'.mes'));verifySavedAttachments(saved,files);} + return {id:created.id,attachmentCount:files.length}; } setInterval(()=>{for(const [token,s] of sessions)if(s.expires