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;in+f.data.length,0)}); +}); +test('attachment count ignores plain text and requires a B2 header',()=>{assert.equal(attachmentSummary(Buffer.from('Body: 4\r\nFile: 3 test\r\n\r\ntext')).attachmentCount,0);}); +test('upload rejects oversize files, too many files, duplicates and unsafe fields before contacting BPQ',async()=>{ + const make=files=>{const f=new FormData();for(const [name,data]of files)f.append('files',new Blob([data]),name);return f;}; + await assert.rejects(readSubmission(await request(make([['large.bin',Buffer.alloc(uploadLimits.bytes+1)]]))),/64 KB/); + await assert.rejects(readSubmission(await request(make(Array.from({length:11},(_,i)=>[i+'.txt','x'])))),/10 allegati/); + await assert.rejects(readSubmission(await request(make([['same.txt','a'],['SAME.txt','b']]))),/duplicati/); + const f=new FormData();f.set('to','a');f.append('to','b');await assert.rejects(readSubmission(await request(f)),/Campi/); + const req=Readable.from([Buffer.from(JSON.stringify({files:[{name:'bypass'}]}))]);req.headers={'content-type':'application/json'};await assert.rejects(readSubmission(req),/caricamento/); +}); +test('filenames cannot inject headers, preserve paths, or silently collide after sanitisation',async()=>{ + const form=new FormData();form.append('files',new Blob(['x']),'../../unsafe;name.txt');const data=await readSubmission(await request(form));assert.equal(data.files[0].name,'unsafe_name.txt'); + const both=new FormData();both.append('files',new Blob(['x']),'one;two.txt');both.append('files',new Blob(['y']),'one_two.txt');await assert.rejects(readSubmission(await request(both)),/duplicati/); +}); +test('saved message is rejected if BPQ drops, truncates or substitutes an attachment',()=>{ + const files=[{name:'test.bin',data:Buffer.from([0,255,1])}];const bytes=b2('test',files);assert.deepEqual(parseAttachments(bytes)[0].data,files[0].data);assert.throws(()=>verifySavedAttachments(b2('test',[]),files),/allegati non corrispondono/);assert.throws(()=>verifySavedAttachments(b2('test',[{...files[0],data:Buffer.from([0,255,2])}]),files),/allegati non corrispondono/);assert.throws(()=>verifySavedAttachments(bytes.subarray(0,bytes.length-4),files),/incompleto/); +}); diff --git a/public/app.js b/public/app.js index 1abcc25..f82ad40 100644 --- a/public/app.js +++ b/public/app.js @@ -2,7 +2,7 @@ const $=s=>document.querySelector(s), $$=s=>[...document.querySelectorAll(s)]; let station={call:'',alias:'',features:{},apps:[]}; let csrf='',allMessages=[],dashboardData=null,filter='all',selected=null,page='home',loadGeneration=0; const esc=v=>String(v??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); -async function api(url,options={}){const r=await fetch('/api'+url,{...options,headers:{'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 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'));} @@ -20,13 +20,13 @@ async function loadMessages(){if(!station.features.bbs)return;try{allMessages=aw 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 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 '+esc(stamp('sent'))+'':'',stamp('received')?'Ricevuto '+esc(stamp('received'))+'':'','Timezone: '+esc(zone)].filter(Boolean).map(x=>''+x+'').join('');} -function mailRow(m,selection,attribute,options={}){const unread=m.status==='N',current=selection===m.id;return ``;} +function mailRow(m,selection,attribute,options={}){const unread=m.status==='N',current=selection===m.id;return ``;} function renderMessages(){const q=$('#search').value.toLowerCase(),cat=$('#category').value;const list=allMessages.filter(m=>(filter==='all'||m.type===filter||filter==='sent'&&m.from.replace(/-\d+$/,'')===station.call.replace(/-\d+$/,''))&&(!cat||m.to===cat)&&(!q||`${m.subject} ${m.from} ${m.to} ${m.id}`.toLowerCase().includes(q)));$('#list-count').textContent=list.length+' messaggi';$('#message-list').innerHTML=list.map(m=>mailRow(m,selected,'data-id',{category:categoryLabel(m),status:m.status==='F'?'Inoltrato':m.status==='N'?'Nuovo':m.status==='Y'?'Letto':m.status==='H'?'Trattenuto':m.status})).join('')||'

Nessun messaggio corrisponde ai filtri.

';$$('#message-list [data-id]').forEach(b=>b.onclick=()=>readMessage(Number(b.dataset.id)));} async function readMessage(id){const generation=++loadGeneration;selected=id;renderMessages();$('#reader').innerHTML='

Caricamento messaggio…

';try{const m=await api('/messages/'+id);if(generation!==loadGeneration)return;$('#reader').innerHTML=`
${m.type==='B'?'BOLLETTINO':'MESSAGGIO PERSONALE'} · #${id}

${esc(m.subject)}

Da ${esc(m.from)}A ${esc(m.to)}${mailTimeMeta(m)}
${readableBody(m.text)}
`;$('#reply').onclick=()=>openCompose({to:m.from,subject:(/^Re:/i.test(m.subject)?m.subject:'Re: '+m.subject).slice(0,80),text:'\n\n--- '+m.from+' ---\n'+m.text.split('\n').map(l=>'> '+l).join('\n')});}catch(err){$('#reader').innerHTML=`

Messaggio non disponibile

${esc(err.message)}

`}} $$('[data-filter]').forEach(b=>b.onclick=()=>{filter=b.dataset.filter;$$('[data-filter]').forEach(x=>x.classList.toggle('active',x===b));renderMessages()});$('#search').oninput=renderMessages;$('#category').onchange=renderMessages; function openCompose(data={}){const f=$('#compose-form');f.reset();for(const [key,value]of Object.entries(data))f.elements[key].value=value;$('#compose-error').textContent='';$('#compose').showModal();f.elements.to.focus()} -$$('.compose-button').forEach(b=>b.onclick=()=>openCompose());$$('.close-compose').forEach(b=>b.onclick=()=>{const f=$('#compose-form');if((f.elements.text.value||f.elements.subject.value)&&!bpqConfirm('Chiudere e scartare questa bozza?'))return;$('#compose').close()}); -$('#compose-form').addEventListener('submit',async e=>{e.preventDefault();const winlinkMode=typeof wlCompose!=='undefined'&&wlCompose;const b=$('#send-button');b.disabled=true;b.textContent='Salvataggio in BPQ…';$('#compose-error').textContent='';try{const data=Object.fromEntries(new FormData(e.target));const created=await api('/messages',{method:'POST',body:JSON.stringify(data)});$('#compose').close();toast('Messaggio #'+created.id+' salvato nella BBS. L’inoltro sarà gestito da BPQ.');if(winlinkMode){navigate('winlink');wlFolder='queue';await wlLoad();wlRender();wlRead(created.id);}else{navigate('bbs');await loadMessages();readMessage(created.id);}loadDashboard();}catch(err){$('#compose-error').textContent=err.message}finally{b.disabled=false;b.textContent='Salva e metti in coda →'}}); +$$('.compose-button').forEach(b=>b.onclick=()=>openCompose());$$('.close-compose').forEach(b=>b.onclick=()=>{const f=$('#compose-form');if((f.elements.text.value||f.elements.subject.value||window.bpqComposeAttachments?.count())&&!bpqConfirm('Chiudere e scartare questa bozza?'))return;$('#compose').close()}); +$('#compose-form').addEventListener('submit',async e=>{e.preventDefault();const winlinkMode=typeof wlCompose!=='undefined'&&wlCompose;const b=$('#send-button');b.disabled=true;b.textContent='Salvataggio in BPQ…';window.bpqComposeAttachments?.busy(true);$('#compose-error').textContent='';try{const data=Object.fromEntries(new FormData(e.target));const payload=winlinkMode&&window.bpqComposeAttachments?.count()?window.bpqComposeAttachments.form(data):JSON.stringify(data);const created=await api('/messages',{method:'POST',body:payload});$('#compose').close();toast('Messaggio #'+created.id+' salvato nella BBS. L’inoltro sarà gestito da BPQ.');if(winlinkMode){navigate('winlink');wlFolder='queue';await wlLoad();wlRender();wlRead(created.id);}else{navigate('bbs');await loadMessages();readMessage(created.id);}loadDashboard();}catch(err){$('#compose-error').textContent=err.message}finally{window.bpqComposeAttachments?.busy(false);b.disabled=false;b.textContent='Salva e metti in coda →'}}); $('#refresh').onclick=async()=>{const b=$('#refresh');b.disabled=true;await Promise.all([loadDashboard(),loadMessages()]);b.disabled=false}; setInterval(()=>{if(csrf&&!document.hidden)loadDashboard()},20000);setInterval(()=>{$('#clock').textContent=new Date().toLocaleTimeString(BPQI18n.locale(),{hour:'2-digit',minute:'2-digit'})+' · '+mailTimezone()},1000); function restoreSession(){api('/session').then(showShell).catch(()=>showLogin());} diff --git a/public/attachments.js b/public/attachments.js index 65d5a37..97bb44d 100644 --- a/public/attachments.js +++ b/public/attachments.js @@ -2,6 +2,6 @@ let attachmentGeneration=0,attachmentPdf=null; const attachmentDialog=document.createElement('dialog');attachmentDialog.className='attachment-dialog';attachmentDialog.innerHTML='

Allegato

';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='
';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(pageCaricamento anteprima…

';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='

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=`${file.mime.startsWith('image/')?'▧':file.mime==='application/pdf'?'PDF':'▤'}
${esc(file.name)}${size(file.size)}${file.reconstructed?' · Ricostruito da '+file.parts+' parti · CRC verificati':''}
Scarica ↓`;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=`7plus · ${esc(data.encoded.name)}

${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.messageIds.map(mid=>'').join('')+'
':''}Scarica testo originale della parte ↓`;section.append(box);box.querySelectorAll('[data-seven-message]').forEach(b=>b.onclick=()=>{navigate('bbs');readMessage(Number(b.dataset.sevenMessage));});}}catch(e){section.innerHTML=`${esc(e.message)}`;}} +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();reader.querySelector('.reader-attachment-count')?.remove();if(data.files.length){const count=document.createElement('span');count.className='reader-attachment-count';count.textContent='📎 '+data.files.length;count.title='Allegati';reader.querySelector('.reader-header .tag')?.after(count);}if(data.files.length){const heading=document.createElement('h3');heading.textContent='Allegati · '+data.files.length;section.append(heading);for(const file of data.files){const row=document.createElement('div');row.className='attachment-row';row.innerHTML=`${file.mime.startsWith('image/')?'▧':file.mime==='application/pdf'?'PDF':'▤'}
${esc(file.name)}${size(file.size)}${file.reconstructed?' · Ricostruito da '+file.parts+' parti · CRC verificati':''}
Scarica ↓`;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=`7plus · ${esc(data.encoded.name)}

${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.messageIds.map(mid=>'').join('')+'
':''}Scarica testo originale della parte ↓`;section.append(box);box.querySelectorAll('[data-seven-message]').forEach(b=>b.onclick=()=>{navigate('bbs');readMessage(Number(b.dataset.sevenMessage));});}}catch(e){section.innerHTML=`${esc(e.message)}`;}} 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'));}; diff --git a/public/compose-attachments.css b/public/compose-attachments.css new file mode 100644 index 0000000..11f8882 --- /dev/null +++ b/public/compose-attachments.css @@ -0,0 +1,32 @@ +#compose{max-height:94dvh;overflow:hidden;padding:0} +#compose-form{display:flex;flex-direction:column;max-height:calc(94dvh - 2px)} +#compose .dialog-heading{flex:none;margin:0;padding:22px 30px 16px;border-bottom:1px solid #2b3a4d} +#compose .compose-scroll-body{min-height:0;overflow:auto;padding:20px 30px;overscroll-behavior:contain} +#compose footer{flex:none;margin:0;padding:15px 30px;border-top:1px solid #2b3a4d;background:#151d28} +.compose-attachments{border:1px dashed #3d5268;border-radius:10px;padding:14px 16px;margin:18px 0;background:#101b29;transition:border-color .15s,background .15s} +.compose-attachments[hidden]{display:none} +.compose-attachments.dragging{border-color:#a6c8ea;background:#1a3045} +.compose-attachments-heading{display:flex;justify-content:space-between;align-items:center;gap:12px} +.compose-attachments-heading>div{display:flex;gap:12px;align-items:center;font-size:12px} +.compose-attachments-heading small{color:#8ca2b6;font-size:10px;font-weight:400} +.compose-attachments-heading button{min-height:34px;padding:7px 12px;font-size:11px} +.compose-file-list{display:grid;gap:7px;margin-top:10px;max-height:170px;overflow:auto} +.compose-file-list:empty{display:none} +.compose-file{display:flex;align-items:center;gap:11px;padding:8px 10px;background:#172638;border:1px solid #2b4157;border-radius:7px;min-width:0} +.compose-file-icon{display:grid;place-items:center;width:36px;height:36px;flex:none;font-size:20px;color:#9fbdd9} +.compose-file-icon img{max-width:36px;max-height:36px;border-radius:4px;object-fit:contain} +.compose-file>div{min-width:0;flex:1}.compose-file b{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:11px;color:#e0eaf4} +.compose-file small{display:block;font-size:10px;color:#8ca2b6;margin-top:4px} +.compose-file-remove{border:0;background:transparent;color:#b2c4d4;width:32px;height:32px;border-radius:6px;font-size:20px;cursor:pointer} +.compose-file-remove:hover{background:#48313b;color:#ffb7bd}.compose-file-remove:focus-visible{outline:2px solid #a6c8ea} +#compose .compose-file-help{font-size:10px;line-height:1.5;color:#8ca2b6;margin:10px 0 0} +.mail-paperclip{display:inline-flex;gap:3px;align-items:center;margin-left:9px;color:#9ebfdf;font-size:10px;vertical-align:middle;white-space:nowrap} +.reader-attachment-count{display:inline-flex;align-items:center;gap:4px;border-radius:5px;background:#263b50;color:#c3d8ec;padding:4px 8px;font-size:10px;margin-left:8px} +@media(max-width:600px){.compose-attachments{padding:12px}.compose-attachments-heading>div{gap:6px;flex-wrap:wrap}.compose-file-list{max-height:130px}} + +#compose:has(.compose-attachments:not([hidden])) textarea{height:120px;min-height:90px} + +#compose:has(.compose-attachments:not([hidden])) .compose-row{grid-template-columns:1fr} + + +@media(max-width:600px){#compose .dialog-heading{padding:18px 20px 14px}#compose .compose-scroll-body{padding:16px 20px}#compose footer{padding:12px 20px}} diff --git a/public/compose-attachments.js b/public/compose-attachments.js new file mode 100644 index 0000000..42f9a71 --- /dev/null +++ b/public/compose-attachments.js @@ -0,0 +1,28 @@ +(() => { + const form=document.querySelector('#compose-form'),panel=document.createElement('section');panel.className='compose-attachments';panel.hidden=true; + panel.innerHTML='
Allegati0 / 64 KB

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)=>'
'+(item.url?'':'📎')+'
'+esc(item.file.name)+''+size(item.file.size)+'
').join(''); + } + function add(incoming){ + if(sending)return;const candidate=[...incoming],error=panel.querySelector('#compose-file-error');error.textContent=''; + if(files.length+candidate.length>10){error.textContent='Massimo 10 allegati per messaggio';return;} + if(total()+candidate.reduce((sum,file)=>sum+file.size,0)>64*1024){error.textContent='Allegati troppo grandi: massimo 64 KB complessivi';return;} + const names=new Set(files.map(item=>item.file.name.toLowerCase())); + for(const file of candidate){if(names.has(file.name.toLowerCase())){error.textContent='Nomi allegati duplicati: rinomina i file';return;}names.add(file.name.toLowerCase());} + files.push(...candidate.map(file=>({file,url:/^image\/(png|jpeg|gif|webp)$/.test(file.type)?URL.createObjectURL(file):null})));render(); + } + panel.querySelector('#compose-file-add').onclick=()=>input.click();input.onchange=()=>{add(input.files);input.value='';}; + list.onclick=e=>{const button=e.target.closest('[data-remove-file]');if(!button||sending)return;const [removed]=files.splice(Number(button.dataset.removeFile),1);if(removed.url)URL.revokeObjectURL(removed.url);panel.querySelector('#compose-file-error').textContent='';render();}; + for(const name of ['dragenter','dragover'])panel.addEventListener(name,e=>{e.preventDefault();if(!sending)panel.classList.add('dragging');}); + panel.addEventListener('dragleave',e=>{if(!panel.contains(e.relatedTarget))panel.classList.remove('dragging');});panel.addEventListener('drop',e=>{e.preventDefault();panel.classList.remove('dragging');add(e.dataTransfer.files);}); + window.bpqComposeAttachments={count:()=>files.length,reset(){files.forEach(item=>{if(item.url)URL.revokeObjectURL(item.url);});files=[];sending=false;input.value='';panel.querySelector('#compose-file-error').textContent='';render();},form(data){const textBytes=new TextEncoder().encode(String(data.text||'').replace(/\r?\n/g,'\r\n')).length;if(textBytes+total()>80*1024)throw new Error(BPQI18n.t('Testo e allegati superano 80 KB complessivi'));const payload=new FormData();for(const [key,value]of Object.entries(data))payload.set(key,value);for(const item of files)payload.append('files',item.file,item.file.name);return payload;},busy(value){sending=value;render();}}; + document.querySelector('#compose').addEventListener('cancel',e=>{if((form.elements.text.value||form.elements.subject.value||files.length)&&!bpqConfirm('Chiudere e scartare questa bozza?'))e.preventDefault();}); + document.addEventListener('bpq-languagechange',render); +})(); diff --git a/public/i18n.js b/public/i18n.js index ff6a565..d4d07fb 100644 --- a/public/i18n.js +++ b/public/i18n.js @@ -609,7 +609,21 @@ Accesso rifiutato|Access denied Collega prima il terminale|Connect the terminal first Invia un solo comando, massimo 1000 caratteri|Send one command, up to 1000 characters `; - const dictionary=new Map(entries.trim().split('\n').map(line=>line.split('|'))); + const uploadCopy=`Allegati|Attachments +Allega file|Attach files +Seleziona allegati|Choose attachments +Rimuovi allegato|Remove attachment +Trascina qui i file oppure selezionali. Massimo 10 file e 64 KB complessivi. Via radio, i file piccoli riducono il tempo di collegamento.|Drop files here or select them. Up to 10 files and 64 KB total. Small files reduce radio connection time. +Massimo 10 allegati per messaggio|Up to 10 attachments per message +Allegati troppo grandi: massimo 64 KB complessivi|Attachments too large: maximum 64 KB total +Nomi allegati duplicati: rinomina i file|Duplicate attachment names: rename the files +Usa il caricamento file per gli allegati|Use file upload for attachments +Campi del messaggio non validi|Invalid message fields +Campo allegato non valido|Invalid attachment field +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.`; + 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('|'))); function resolveLanguage(preference=null,languages=[]){ if(preference==='it'||preference==='en')return preference; // The first browser language is the user's preferred UI language; English is the fallback. diff --git a/public/index.html b/public/index.html index 74e58ed..3e6b3f1 100644 --- a/public/index.html +++ b/public/index.html @@ -1,5 +1,5 @@ -BPQ Console +BPQ Console