feat: accept sheets of up to 5 GB end to end
Some checks failed
Build and deploy / Validate source (push) Successful in 12s
Build and deploy / Integration suite on a real stack (push) Failing after 2m36s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Has been skipped

Sheets of several GB are the normal order. The upload limit is now 5 GB.
ClamAV scans files up to 2 GB; a larger file is released only when its
first bytes match the format its name claims, and a disguised file is
refused. The Site grades a sheet over 150 MB from the pixel size in its
PNG, JPEG or WebP header without decoding it, and reads large PDFs in
ranges. The worker never opens a source over 300 MB: a finished sheet
placed whole becomes its own print file, which the Kanban offers to approve
as the final, and anything else goes to hand preparation. Files start
uploading as they enter the cart, with progress in the summary, and each
part renews the reservation so slow uploads do not expire. Quotas grow to
50 GB per customer and 500 GB in total; the Swarm config for ClamAV is
renamed because a deployed config cannot change in place.

Verified locally with a 386 MB and a 1.8 GB PNG (scanned, paid, original
as print file), a 2.3 GB PNG (format check) and a disguised 2.3 GB file
(refused).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-09-29 13:18:18 -03:00
parent 4437232d27
commit 5f2be7ea20
21 changed files with 329 additions and 54 deletions

View File

@@ -45,8 +45,7 @@
ready.then(session=>{
window.dtfUploadMaxBytes=session.max_upload_bytes;
const limit=document.getElementById('zLimite');
if(limit)limit.textContent='Até '+(session.max_upload_bytes/1048576).toFixed(0)+
' MB por arquivo enquanto a verificação de segurança para arquivos grandes é preparada.';
if(limit)limit.textContent='Até '+(session.max_upload_bytes/1073741824).toFixed(0)+' GB por arquivo.';
}).catch(()=>{});
window.dtfSessionReady=ready;
window.dtfApi=api;
@@ -93,9 +92,52 @@
message('Nenhum pedido aguardando pagamento.');
button('Ir para o carrinho', () => vaiPara(CARRINHO));
}
// Files start uploading as soon as they are in the cart, so a sheet of
// several GB is on its way while the customer fills in the order. The
// checkout waits for whatever is still going.
const envios=new Map();
const chaveArquivo=f=>[f.name,f.size,f.lastModified].join('|');
function enviar(file) {
const k=chaveArquivo(file);
let e=envios.get(k);
if (!e) {
e={file, sent:0, done:false, failed:null};
e.promise=(async()=>{
const session=await ready;
return window.dtfUpload(file,{api,scope:session.cart_scope,progress:()=>{},
onBytes:n=>{e.sent=n;pintaEnvio();}});
})();
e.promise.then(()=>{e.done=true;pintaEnvio();},
error=>{e.failed=error;envios.delete(k);pintaEnvio();});
envios.set(k,e);
}
return e.promise;
}
const arquivosDoCarrinho=()=>[...pedido,...(busy&&itemAtual?[itemAtual]:[])].flatMap(it=>it.localFiles||[]);
const gb=n=>(n/1073741824).toLocaleString('pt-BR',{maximumFractionDigits:1})+' GB';
const mb=n=>n>=1073741824 ? gb(n) : Math.round(n/1048576)+' MB';
function textoEnvio() {
const files=arquivosDoCarrinho(); if(!files.length) return '';
let total=0, sent=0, pendentes=0;
for (const f of files) {
const e=envios.get(chaveArquivo(f));
total+=f.size; sent+=e ? Math.min(e.sent,f.size) : 0;
if (!e || !e.done) pendentes++;
}
if (!pendentes) return 'Arquivos enviados.';
if (sent>=total) return 'Arquivos enviados · verificando a segurança…';
return 'Enviando seus arquivos: '+Math.floor(sent/total*100)+'% ('+mb(sent)+' de '+mb(total)+')';
}
function pintaEnvio() {
const el=document.getElementById('envioArq');
const texto=textoEnvio();
if (el) el.textContent=texto;
if (busy && texto) message(texto);
}
// Only what is in the cart: the item on the product page may still change.
window.addEventListener('dtf-cart-changed',()=>{ arquivosDoCarrinho().forEach(f=>{ enviar(f).catch(()=>{}); }); pintaEnvio(); });
async function upload(file) {
const session=await ready;
return window.dtfUpload(file,{api,progress:message,scope:session.cart_scope});
return enviar(file);
}
// The cart's package: billed metres and value. The charged freight is
// quoted again by the server from the approved items.
@@ -148,6 +190,7 @@
await ready;
if((await api('/session')).cart_scope !== (await ready).cart_scope) throw new Error('Sua conta ou sessão mudou. Recarregue a página antes de enviar o carrinho.');
const items=[];
pintaEnvio();
for (const item of cart) {
if (!item.localFiles?.length) throw new Error('Selecione novamente os arquivos deste item.');
const uploads=[];

View File

@@ -969,7 +969,7 @@ footer a:hover{color:var(--laranja2)}
<div class="zona" id="zona" tabindex="0" role="button">
<div class="ico">↑</div>
<b id="zTit">Arraste aqui</b><span id="zSub"></span>
<span id="zLimite">Até 128 MB por arquivo enquanto a verificação de segurança para arquivos grandes é preparada.</span>
<span id="zLimite">Até 5 GB por arquivo.</span>
<span class="bt">ou escolher no computador</span>
</div>
<div class="recusa" id="recusa" style="display:none"></div>
@@ -1203,6 +1203,7 @@ footer a:hover{color:var(--laranja2)}
<button id="bPagar">Ir para o pagamento</button>
<button id="bMais" class="sec">Continuar comprando</button>
</div>
<p class="envioArq" id="envioArq" role="status" aria-live="polite"></p>
</aside>
</div>

View File

@@ -324,14 +324,16 @@ function itemCard(order,item,index){
const file=node('div',undefined,'file');
if(row){
const tone=row.status==='ready'?'ok':row.status==='manual'||row.status==='failed'?'warn':'muted';
const label=node('span',PRINT_TEXT[row.status]+(row.status==='ready'&&row.name?' · '+row.name:'')+(row.status==='manual'&&row.detail.reason?': '+row.detail.reason:''),tone);
const original=row.status==='ready'&&row.detail?.source==='original';
const label=node('span',(original?'Arquivo grande: o original é o arquivo de impressão':PRINT_TEXT[row.status])+
(row.status==='ready'&&row.name?' · '+row.name:'')+(row.status==='manual'&&row.detail.reason?': '+row.detail.reason:''),tone);
file.append(tone==='ok'?icon(ICON_OK):tone==='warn'?icon(ICON_WARN):'',label);
if(row.status==='ready'&&row.detail){body.append(file,node('div',[row.detail.film_width_cm+' × '+row.detail.height_cm+' cm',
if(row.status==='ready'&&row.detail&&!original){body.append(file,node('div',[row.detail.film_width_cm+' × '+row.detail.height_cm+' cm',
row.detail.min_dpi?'menor resolução '+row.detail.min_dpi+' DPI':'',row.detail.vector_sources?'PDF vetorial':''].filter(Boolean).join(' · '),'line'));}
else body.append(file);
}else body.append(node('div','Arquivo de impressão ainda não gerado','line'));
const buttons=node('div',undefined,'buttons');
if(row?.status==='ready')buttons.append(button('Baixar PDF',download(row.upload_id)));
if(row?.status==='ready'&&row.detail?.source!=='original')buttons.append(button('Baixar PDF',download(row.upload_id)));
item.uploads.forEach((uid,i)=>buttons.append(button(item.uploads.length>1?'Original '+(i+1):'Baixar original',download(uid),'btn ghost')));
if(spec?.placements)buttons.append(button('Manifesto',()=>manifest(spec),'btn ghost'));
if(['rec','tra'].includes(order.state)&&(!row||row.status==='manual'||row.status==='failed'))
@@ -360,7 +362,7 @@ function finalsSection(order,revisions,section){
if(generated){
const use=node('input');use.type='checkbox';use.checked=true;use.dataset.useGenerated=index;input.required=false;input.hidden=true;
use.onchange=()=>{input.hidden=use.checked;input.required=!use.checked;};
const choice=node('label',undefined,'check');choice.append(use,'Usar o PDF gerado ('+generated.name+')');
const choice=node('label',undefined,'check');choice.append(use,(generated.detail?.source==='original'?'Usar o original como arquivo final (':'Usar o PDF gerado (')+generated.name+')');
slot.append(choice);input.generated=()=>use.checked?generated.upload_id:null;
}
slot.append(input);form.append(slot);return input;

View File

@@ -139,9 +139,55 @@ async function rasterizarPdf(file, larguraCm, alturaCm){
return result||{erro:'não deu para conferir',semWorker:temWorker===false};
}
// Sheets of several GB are the normal order. The browser cannot decode an image
// that size (it would freeze or crash the tab), and it does not need to: the
// grade comes from the width in pixels, which PNG, JPEG and WebP store in their
// first bytes. Above GRANDE_BYTES only those bytes are read.
const GRANDE_BYTES=150*1048576;
async function dimensoesImagem(file){
const b=new Uint8Array(await file.slice(0,Math.min(file.size,4*1048576)).arrayBuffer());
const u16=(i,le)=>le? b[i]|(b[i+1]<<8) : (b[i]<<8)|b[i+1];
const u32=(i)=>((b[i]<<24)>>>0)+(b[i+1]<<16)+(b[i+2]<<8)+b[i+3];
if(b[0]===0x89 && b[1]===0x50 && b[2]===0x4E && b[3]===0x47) // PNG · IHDR
return {w:u32(16), h:u32(20)};
if(b[0]===0xFF && b[1]===0xD8){ // JPEG · SOFn
let i=2;
while(i+9<b.length){
if(b[i]!==0xFF){ i++; continue; }
const m=b[i+1], len=u16(i+2);
if(m>=0xC0 && m<=0xCF && ![0xC4,0xC8,0xCC].includes(m)) return {w:u16(i+7), h:u16(i+5)};
i+=2+len;
}
return null;
}
const tag=String.fromCharCode(...b.slice(8,16));
if(String.fromCharCode(...b.slice(0,4))==='RIFF' && tag.startsWith('WEBP')){ // WebP
if(tag==='WEBPVP8X') return {w:1+(b[24]|(b[25]<<8)|(b[26]<<16)), h:1+(b[27]|(b[28]<<8)|(b[29]<<16))};
if(tag==='WEBPVP8L'){ const n=b[21]|(b[22]<<8)|(b[23]<<16)|(b[24]<<24); return {w:(n&0x3FFF)+1, h:((n>>14)&0x3FFF)+1}; }
if(tag==='WEBPVP8 ') return {w:u16(26,true)&0x3FFF, h:u16(28,true)&0x3FFF};
}
return null;
}
// Large PDFs are read in ranges, never loaded whole into memory.
async function fontePdf(lib, file){
if(file.size<=GRANDE_BYTES) return {data:await file.arrayBuffer()};
const inicio=new Uint8Array(await file.slice(0,262144).arrayBuffer());
const t=new lib.PDFDataRangeTransport(file.size, inicio);
t.requestDataRange=(de,ate)=>{ file.slice(de,ate).arrayBuffer().then(buf=>t.onDataRange(de,new Uint8Array(buf))); };
return {range:t, rangeChunkSize:262144, disableAutoFetch:true, disableStream:true};
}
function medirFolha(file){
return new Promise(res=>{
const nome=(file.name||'').toLowerCase();
if(RENDERIZA.test(nome) && file.size>GRANDE_BYTES){
dimensoesImagem(file).then(d=>{
if(!d || !(d.w>0) || !(d.h>0)) return res(null);
const L=larguraFilme();
res({larg:L, alt:+(d.h/d.w*L).toFixed(1), fonte:'dimensões do arquivo',
dpiFolha:Math.round(d.w/(L/2.54)), px:d.w, grande:true});
}).catch(()=>res(null));
return;
}
if(RENDERIZA.test(nome)){
carregarImagem(file).then(img=>{
if(!img || !img.width) return res(null);
@@ -160,7 +206,7 @@ function medirFolha(file){
let doc=null;
carregarPdfJs().then(async lib=>{
if(!lib) throw new Error('Não foi possível carregar o leitor de PDF.');
doc=await lib.getDocument({data:await file.arrayBuffer(),
doc=await lib.getDocument({...await fontePdf(lib,file),
disableFontFace:true, isEvalSupported:false, useSystemFonts:false,
verbosity:0}).promise;
if(doc.numPages!==1)
@@ -207,7 +253,10 @@ function pintaFolha(){
let medida='';
if(lido){
const a=x.an;
const conferido = a
const conferido = a && a.grande
? '<div class="conf"><b>Arquivo grande · '+a.dpi+' DPI</b>'+
'<span>nota pela resolução · peças, resíduos e fundo conferidos pela equipe</span></div>'
: a
? '<div class="conf"><b>Conferido de verdade</b>'+
'<span>'+a.artes+' peça'+(a.artes===1?'':'s')+' · '+a.aproveitamento+
'% da folha virou arte · '+

View File

@@ -45,15 +45,16 @@ function avaliar(){
? 'média por área das imagens dentro do PDF · pior em '+
Math.min(...ans.map(a=>a.res? a.res.pior : a.dpi))+' DPI'
: 'resolução do arquivo · arte ampliada antes de exportar não aparece aqui'],
['ok', soma('artes')+' peças na folha',
ans.some(a=>a.grande) ? ['ok','Arquivo grande','peças, resíduos e fundo conferidos pela equipe'] : null,
ans.some(a=>a.grande) ? null : ['ok', soma('artes')+' peças na folha',
Math.round(soma('aproveitamento')/ans.length)+'% da folha virou arte'],
soma('residuos') ? ['er','Resíduo de recorte',
ans.some(a=>a.grande) ? null : soma('residuos') ? ['er','Resíduo de recorte',
soma('residuos')+' ponto'+(soma('residuos')>1?'s':'')+' abaixo de 2 mm · a impressora imprime']
: ['ok','Sem resíduo de recorte','nada solto na folha'],
soma('encostadas') ? ['fix', soma('encostadas')+' peças a menos de 5 mm',
ans.some(a=>a.grande) ? null : soma('encostadas') ? ['fix', soma('encostadas')+' peças a menos de 5 mm',
'se forem artes diferentes, separamos com 5 mm sem custo']
: ['ok','Espaço entre peças','nenhuma abaixo de 6 mm'],
ans.some(a=>a.fundoChapado) ? ['er','Fundo chapado','a folha está sem transparência']
ans.some(a=>a.grande) ? null : ans.some(a=>a.fundoChapado) ? ['er','Fundo chapado','a folha está sem transparência']
: ['ok','Fundo transparente','canal alfa conferido'],
null
].filter(Boolean);

View File

@@ -37,14 +37,13 @@ function sel(fs){
const fora = fs.filter(f=>!regra.test(f.name));
fs = fs.filter(f=>regra.test(f.name));
recusa(fora);
const max=window.dtfUploadMaxBytes||128*1048576;
const max=window.dtfUploadMaxBytes||5*1073741824;
const grandes=fs.filter(f=>f.size>max);
if(grandes.length){
const el=$('recusa');
el.style.display='block';
el.innerHTML='<b>Arquivo acima do limite de '+(max/1048576).toFixed(0)+
' MB.</b> A verificação de segurança ainda não consegue liberar arquivos maiores. '+
'Divida ou compacte a arte antes de enviar.';
el.innerHTML='<b>Arquivo acima do limite de '+(max/1073741824).toFixed(0)+
' GB.</b> Divida a folha em partes menores antes de enviar.';
fs=fs.filter(f=>f.size<=max);
}
if(!fs.length) return;
@@ -75,12 +74,21 @@ function sel(fs){
}
if(md && md.dpiFolha!=null && md.dpiFolha<DPI_RECUSA) return recusaFolha(x, md);
x.med=md; if(md) x.m=md.alt/100; x.pct=55; pintaFolha();
if(md && RENDERIZA.test(x.f.name)){
if(md && md.grande){
// Graded from its size in pixels; the pieces, gaps and background
// are checked by the team, since the image is never opened here.
x.an={dpi:md.dpiFolha, grande:true, artes:0, residuos:0, encostadas:0,
fundoChapado:false, aproveitamento:0, alturaCm:md.alt, fonteDpi:'arquivo'};
x.pct=null; pintaFolha();
}else if(md && RENDERIZA.test(x.f.name)){
carregarImagem(x.f).then(img=>{
if(img){ x.previewSrc=img.src; try{ x.an=analisarFolha(img, md.larg); if(x.an) x.an.fonteDpi='arquivo'; }
catch(e){} }
x.pct=null; pintaFolha();
});
}else if(md && /\.pdf$/i.test(x.f.name) && x.f.size>GRANDE_BYTES){
x.semAnalise='PDF grande: a resolução das imagens de dentro é conferida pela equipe';
x.pct=null; pintaFolha();
}else if(md && /\.pdf$/i.test(x.f.name)){
x.pct=70; pintaFolha();
rasterizarPdf(x.f, md.larg, md.alt).then(r=>{

View File

@@ -228,6 +228,8 @@ section+section{border-top:0}
/* The payment pages: paying on the left, the order summary on the right */
html:is([data-rota="pagamento"],[data-rota="pix"]) .checkout{max-width:1040px;margin-top:8px}
html:is([data-rota="pagamento"],[data-rota="pix"]) .pagGrid{display:grid;grid-template-columns:minmax(0,1fr) 340px;gap:32px;align-items:start}
.envioArq{font-size:13px;color:var(--texto2);margin-top:12px;line-height:1.5}
.envioArq:empty{display:none}
.dicaEnd{font-size:13px;color:var(--texto2);margin-top:12px}
.dicaEnd:empty{display:none}
.pagCab{display:flex;align-items:baseline;justify-content:space-between;gap:16px;margin-bottom:20px}

View File

@@ -1,5 +1,5 @@
/* Shared direct multipart transport for customer originals/corrections and operator finals. */
window.dtfUpload = async (file, {api, prefix='/uploads', startPath=prefix, progress=()=>{}, scope='guest', resume=true}) => {
window.dtfUpload = async (file, {api, prefix='/uploads', startPath=prefix, progress=()=>{}, onBytes=()=>{}, scope='guest', resume=true}) => {
const samples=new Blob([file.slice(0,65536),file.slice(Math.max(0,file.size-65536))]);
const hash=Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',await samples.arrayBuffer())),b=>b.toString(16).padStart(2,'0')).join('');
const key='dtf-upload:'+JSON.stringify([scope,file.name,file.size,file.lastModified,hash]);
@@ -7,7 +7,11 @@ window.dtfUpload = async (file, {api, prefix='/uploads', startPath=prefix, progr
if(id){try{state=await api(prefix+'/'+id);}catch(error){if(![404,410].includes(error.status))throw error;id=null;}}
if(!id){state=await api(startPath,{name:file.name,size:file.size});id=state.id;if(resume)localStorage.setItem(key,id);}
async function waitForScan(){
for(let attempt=0;attempt<150;attempt++){
onBytes(file.size);
// The antivirus streams the whole file: about a second per 2 MB, and at
// least two and a half minutes.
const attempts=Math.max(150,Math.ceil(file.size/2e6));
for(let attempt=0;attempt<attempts;attempt++){
const checked=await api(prefix+'/'+id);
if(checked.scan_state==='clean')return id;
if(['rejected','error'].includes(checked.scan_state))throw new Error(checked.scan_reason||'Arquivo bloqueado pela verificação de segurança.');
@@ -18,12 +22,15 @@ window.dtfUpload = async (file, {api, prefix='/uploads', startPath=prefix, progr
}
if(state.complete)return waitForScan();
const done=new Set(state.parts||[]),size=state.part_bytes;
onBytes(Math.min(file.size,done.size*size));
for(let offset=0,part=1;offset<file.size;offset+=size,part++){
if(done.has(part))continue;
progress('Enviando '+file.name+' · parte '+part+'/'+Math.ceil(file.size/size));
const signed=await api(prefix+'/'+id+'/parts/'+part,{});
const response=await fetch(signed.url,{method:'PUT',body:file.slice(offset,offset+size)});
if(!response.ok)throw new Error('Upload interrompido. Tente novamente para retomar.');
done.add(part);
onBytes(Math.min(file.size,done.size*size));
}
await api(prefix+'/'+id+'/complete',{});
return waitForScan();