diff --git a/app/scanning.py b/app/scanning.py index 708b70a..c858970 100644 --- a/app/scanning.py +++ b/app/scanning.py @@ -75,6 +75,37 @@ RIFF_FORMS = {'cdr': re.compile(rb'^RIFF....CDR', re.S), 'webp': re.compile(rb'^ HEAD_BYTES = 64 +# Dropstar's rule D-13 (2026-10-26): the content decides a file's type, never +# its extension. A third of their ".cdr" files are PDFs renamed. +def detected_format(head): + """The format a file's first bytes show, as an extension, or None.""" + for ext in ('pdf', 'png', 'jpg', 'tif', 'psd'): + if any(head.startswith(sig) for sig in SIGNATURES[ext]): + return ext + for ext, form in RIFF_FORMS.items(): + if form.match(head): + return ext + return None + + +def real_name(name, head): + """The file's name with the extension of what it really is: a ".cdr" that + is a PDF is "x.pdf", a JPG called ".png" is "x.jpg". A name its content + agrees with stays, so an Illustrator file, which is a PDF inside, is still + ".ai" and handled by hand; unknown content keeps the name too.""" + found = detected_format(head) + if not found or format_matches(name, head): + return name + stem, dot, _ = name.rpartition('.') + return (stem if dot else name) + '.' + found + + +def head_of(storage, row): + """A stored file's first bytes.""" + return storage.client.get_object(Bucket=storage.bucket, Key=row['object_key'], + Range=f'bytes=0-{HEAD_BYTES - 1}')['Body'].read() + + def format_matches(name, head): """Whether a file's first bytes are those of the format its name claims.""" ext = name.rsplit('.', 1)[-1].lower() if '.' in name else '' @@ -83,11 +114,10 @@ def format_matches(name, head): return any(head.startswith(sig) for sig in SIGNATURES.get(ext, ())) -def check_large(storage, row): +def check_large(head, row): """Release decision for a file above the antivirus limit.""" - head = storage.client.get_object(Bucket=storage.bucket, Key=row['object_key'], - Range=f'bytes=0-{HEAD_BYTES - 1}')['Body'].read() - if format_matches(row['name'], head): + # The content decides (D-13): a ".cdr" that is a PDF is still a PDF. + if format_matches(row['name'], head) or detected_format(head): return 'clean', 'Acima do limite do antivírus; formato do arquivo conferido' return 'rejected', 'O conteúdo do arquivo não corresponde ao formato do nome' @@ -99,19 +129,25 @@ def scan_one(storage, scanner=None): AND expires_at>now() AND scan_state IN ('pending','error') AND scan_after<=now() ORDER BY created_at FOR UPDATE SKIP LOCKED LIMIT 1''').fetchone() if not row:return False + name=row['name'] try: + # Every later decision reads the stored name (the manual charge, + # the JPG refusal, the grade, the print file, the folders), so the + # name is made to say what the file is (D-13). + head=head_of(storage,row) + name=real_name(name,head) if row['size'] > scan_limit_bytes(): - state,reason=check_large(storage,row) + state,reason=check_large(head,row) else: stream=storage.client.get_object(Bucket=storage.bucket,Key=row['object_key'])['Body'] try:state,reason=scanner.scan(stream,row['size']) finally:stream.close() except Exception: state,reason='error','Malware scanner unavailable; file remains blocked' - c.execute("""UPDATE dtf_local.uploads SET scan_state=%s,scan_reason=%s,scanned_at=now(), + c.execute("""UPDATE dtf_local.uploads SET name=%s,scan_state=%s,scan_reason=%s,scanned_at=now(), scan_after=now()+interval '1 minute', expires_at=CASE WHEN %s IN ('rejected','error') THEN LEAST(expires_at,now()+interval '3 days') ELSE expires_at END - WHERE id=%s""",(state,reason,state,row['id'])) + WHERE id=%s""",(name,state,reason,state,row['id'])) audit('artwork_scan', upload=str(row['id']), result=state) return True diff --git a/docs/CONTEXT.md b/docs/CONTEXT.md index 5ca46bf..4723fe3 100644 --- a/docs/CONTEXT.md +++ b/docs/CONTEXT.md @@ -196,6 +196,20 @@ amount is the client's to set. The Site reads it from `/api/session` and shows it before checkout (product page, help text, price table); `app/core/pricing.py` charges it. +What a file is comes from its first bytes, never from its name (Dropstar's +rule D-13, 2026-10-26; a third of their ".cdr" files are PDFs). The Site reads +the first bytes when a file is chosen and renames it to its real extension +(`nomeReal` in web/site-upload.js): a ".cdr" that is a PDF becomes ".pdf" and +is measured and checked as a PDF, without the manual charge; a JPG called +".png" is refused as a JPG, naming the file. The server does the same when it +scans an upload (`real_name` in app/scanning.py) and stores the real name, so +every later decision that reads the name (the manual charge, the JPG refusal, +the grade, the original used as its own print file, the folder file names) +follows the content even if the browser was bypassed. A name its content +agrees with stays: an Illustrator ".ai" is a PDF inside but is still handled +by hand, since one saved without PDF content prints a placeholder page. A file +too large for the antivirus passes when its content is any accepted format. + ## Freight **Current (2026-10-15):** the cart quotes every carrier configured at once and @@ -448,13 +462,14 @@ Still to do (2026-10-26): money stays as the customer's credit in their financial control (D-15, the Kanban's cancel text says so, nothing on the Site); the Kanban keeps deleting Finalizado files after 30 days; the footer gets the white spot. -- Still open from the internal rules (docs received 2026-10-26): file type by - its first bytes (D-13), every order's origin and a manual order entry in - the Kanban (D-21, D-35; also how orders paid with credit come in), the - and the rework register (D-02 to D-04). Done 2026-10-27: the folders catch - up on what passed while the Kanban computer was off, and time in - "Aguardando contato" no longer counts in Números' time figures (D-38; each - wait is kept in dtf_local.contact_waits, from mark to clear). +- Still open from the internal rules (docs received 2026-10-26): every + order's origin and a manual order entry in the Kanban (D-21, D-35; also how + orders paid with credit come in), and the rework register (D-02 to D-04). + Done 2026-10-27: the folders catch up on what passed while the Kanban + computer was off, time in "Aguardando contato" no longer counts in Números' + time figures (D-38; each wait is kept in dtf_local.contact_waits, from mark + to clear), and a file's type comes from its first bytes (D-13, see the + commercial rules). - Settled on 2026-10-26: the DTF SITE category (986932924, CATEGORY in app/tiny.py), the white spot also under the print PDF's footer (nothing to change here), and the montador's order format (customer, files, product, the batch with diff --git a/tests/artwork_browser_test.mjs b/tests/artwork_browser_test.mjs index 76ec7be..84ede71 100644 --- a/tests/artwork_browser_test.mjs +++ b/tests/artwork_browser_test.mjs @@ -167,14 +167,14 @@ try{ assert.deepEqual(await evaluate(`({shown:!$('tipoEnvio').hidden, on:[...document.querySelectorAll('#tipoEnvio .cam.on')].map(b=>b.dataset.tipo)})`), {shown:true,on:['folha']}); - await evaluate(`(()=>{const f=new File(['x'],'oversize.cdr');Object.defineProperty(f,'size',{value:1073741824+1});sel([f]);})()`); + await evaluate(`(()=>{const f=new File(['x'],'oversize.cdr');Object.defineProperty(f,'size',{value:1073741824+1});return sel([f]);})()`); assert.equal(await evaluate(`folhas.length===0 && $('recusa').textContent.includes('1 GB')`),true, 'files beyond the 1 GB upload limit are rejected before browser analysis'); // A large sheet (here 900 MB) is the normal order: graded from the pixel size in its // header, never decoded. 6732 x 35433 px across 57 cm is 3 m at 300 DPI. await evaluate(`(()=>{const h=new Uint8Array(33);h.set([0x89,0x50,0x4E,0x47,0x0D,0x0A,0x1A,0x0A,0,0,0,13,0x49,0x48,0x44,0x52]); const v=new DataView(h.buffer);v.setUint32(16,6732);v.setUint32(20,35433);h.set([8,6,0,0,0],24); - const f=new File([h],'folha-grande.png');Object.defineProperty(f,'size',{value:900*1048576});sel([f]);})()`); + const f=new File([h],'folha-grande.png');Object.defineProperty(f,'size',{value:900*1048576});return sel([f]);})()`); await waitFor(()=>evaluate(`folhas.length===1 && !!folhas[0].an`),'large sheet graded from its header'); assert.deepEqual(await evaluate(`({grande:folhas[0].an.grande,dpi:folhas[0].an.dpi,alt:folhas[0].med.alt,preview:!!folhas[0].previewSrc})`), {grande:true,dpi:300,alt:300,preview:false}); @@ -185,11 +185,14 @@ try{ // 2026-10-23), with the reason, before anything is read. await evaluate(`sel([new File(['x'],'arte.jpg',{type:'image/jpeg'})])`); assert.equal(await evaluate(`artes.length===0 && $('recusa').textContent.includes('JPG não dá para enviar')`),true); + // The content decides, not the name (D-13): a JPG called ".png" is refused as a JPG. + await evaluate(`sel([new File([new Uint8Array([0xFF,0xD8,0xFF,0xE0])],'disfarce.png',{type:'image/png'})])`); + assert.equal(await evaluate(`artes.length===0 && $('recusa').textContent.includes('disfarce.png é JPG')`),true); // A large WebP artwork cannot be read in parts: it is measured from its // header and placed as a full box, with its grade, instead of refused. await evaluate(`(()=>{const h=new Uint8Array(30);h.set([0x52,0x49,0x46,0x46,0,0,0,0,0x57,0x45,0x42,0x50,0x56,0x50,0x38,0x58]); h.set([0x39,0x09,0x00,0x39,0x09,0x00],24); - const f=new File([h],'arte-grande.webp');Object.defineProperty(f,'size',{value:400*1048576});sel([f]);})()`); + const f=new File([h],'arte-grande.webp');Object.defineProperty(f,'size',{value:400*1048576});return sel([f]);})()`); await waitFor(()=>evaluate(`artes.length===1 && artes[0].semPrevia===true`),'large WebP artwork measured from its header'); await fill('[data-cm]',20); await waitFor(()=>evaluate(`!!itemAtual?.production?.sources?.length`),'large WebP artwork packed'); @@ -375,6 +378,12 @@ try{ assert.equal(await evaluate(`avaliar().pronto`),false); assert.equal(await evaluate(`cartPodeEnviar()`),false); assert.match(await evaluate(`$('lista').textContent`),/não pode ser orçado/); + // A ".cdr" that is a PDF (D-13) is renamed and measured as a PDF, not handled by hand. + await click('#bVoltar');await click('[data-modo="file"]'); + await evaluate(`sel([${pdfFile(pdfData(),'folha.cdr')}])`); + await waitFor(()=>evaluate(`folhas.length===1 && !!(folhas[0].med || folhas[0].measurementError)`),'renamed PDF measured'); + assert.deepEqual(await evaluate(`({name:folhas[0].f.name,measured:!!folhas[0].med,manual:folhaManual()})`), + {name:'folha.pdf',measured:true,manual:false}); await click('#bVoltar');await click('[data-modo="avulsa"]'); await evaluate(`sel([new File(['not an image'],'broken.png',{type:'image/png'})])`); await waitFor(()=>evaluate('artes.length===1 && artes[0].decodeError===true'),'failed image decode'); diff --git a/tests/browser_test.mjs b/tests/browser_test.mjs index c3e4c22..1ad3325 100644 --- a/tests/browser_test.mjs +++ b/tests/browser_test.mjs @@ -52,7 +52,7 @@ try{ await waitFor(()=>site.eval('typeof window.dtfCheckout === "function"'),'checkout bridge'); // Prove escaping itself, independently of the CSP's second line of defense. await site.call('Page.setBypassCSP',{enabled:true}); - await site.eval(`(()=>{window.xssProbe=0;abrir('file');sel([new File(['test'],'.cdr')]);})()`); + await site.eval(`(()=>{window.xssProbe=0;abrir('file');return sel([new File(['test'],'.cdr')]);})()`); await pause(500); assert.equal(await site.eval('window.xssProbe'),0); assert.equal(await site.eval('document.querySelectorAll("#lista img[onerror]").length'),0); diff --git a/tests/test_large_files.py b/tests/test_large_files.py index 58f463a..721675f 100644 --- a/tests/test_large_files.py +++ b/tests/test_large_files.py @@ -2,7 +2,7 @@ import unittest from app.printjobs import whole_sheet -from app.scanning import format_matches +from app.scanning import check_large, format_matches, real_name ROW = {'id': 'u1', 'name': 'folha.png', 'size': 3 * 1024 ** 3, 'scan_state': 'clean', 'purged_at': None, 'expired': False} @@ -37,6 +37,20 @@ class FormatTest(unittest.TestCase): self.assertFalse(format_matches('a.png', b'%PDF-1.4')) self.assertFalse(format_matches('semextensao', b'\x89PNG\r\n\x1a\n')) + def test_the_content_names_the_file(self): + # Dropstar's rule D-13: a ".cdr" that is a PDF is a PDF, a JPG called + # ".png" is a JPG; a name its content agrees with stays (".ai" is a PDF inside). + self.assertEqual(real_name('folha.cdr', b'%PDF-1.7'), 'folha.pdf') + self.assertEqual(real_name('arte.png', b'\xff\xd8\xff\xe0'), 'arte.jpg') + self.assertEqual(real_name('semextensao', b'%PDF-1.4'), 'semextensao.pdf') + for name, head in (('folha.cdr', b'RIFF\0\0\0\0CDR9'), ('arte.ai', b'%PDF-1.5'), ('arte.ai', b'%!PS-Adobe'), + ('foto.jpeg', b'\xff\xd8\xff'), ('arte.png', b'GIF89a')): + self.assertEqual(real_name(name, head), name, (name, head)) + + def test_a_large_file_passes_on_its_content(self): + self.assertEqual(check_large(b'%PDF-1.7', {'name': 'folha.cdr'})[0], 'clean') + self.assertEqual(check_large(b'MZ\x90\x00', {'name': 'folha.cdr'})[0], 'rejected') + if __name__ == '__main__': unittest.main() diff --git a/web/site-upload.js b/web/site-upload.js index 76b0d18..c01112d 100644 --- a/web/site-upload.js +++ b/web/site-upload.js @@ -7,13 +7,38 @@ function escapeHTML(value){ return String(value).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); } +// Dropstar's rule D-13 (2026-10-26): what a file is comes from its first bytes, +// never from its name. A ".cdr" that is a PDF is renamed ".pdf" and checked as +// a PDF, without the manual charge; a JPG called ".png" is refused as a JPG. +// A name its content agrees with stays, so an Illustrator file, a PDF inside, +// is still ".ai". The same signatures as the server (app/scanning.py). +const TIFF_INICIOS=['II*\0','MM\0*','II+\0','MM\0+']; +const INICIOS={png:['\x89PNG\r\n\x1a\n'], jpg:['\xff\xd8\xff'], jpeg:['\xff\xd8\xff'], + tif:TIFF_INICIOS, tiff:TIFF_INICIOS, pdf:['%PDF-'], ai:['%PDF-','%!PS'], psd:['8BPS'], psb:['8BPS']}; +const RIFF_TIPOS={cdr:/^RIFF[\s\S]{4}CDR/, webp:/^RIFF[\s\S]{4}WEBP/}; +const confere=(ext,ini)=>RIFF_TIPOS[ext] ? RIFF_TIPOS[ext].test(ini) : (INICIOS[ext]||[]).some(a=>ini.startsWith(a)); +const formatoDe=ini=>['pdf','png','jpg','tif','psd','cdr','webp'].find(e=>confere(e,ini))||null; +async function nomeReal(f){ + let ini; + try{ ini=String.fromCharCode(...new Uint8Array(await f.slice(0,16).arrayBuffer())); } + catch(e){ return f; } + const real=formatoDe(ini); + if(!real || confere(extDe(f.name).toLowerCase(),ini)) return f; + const ponto=f.name.lastIndexOf('.'); + const g=new File([f], (ponto>0?f.name.slice(0,ponto):f.name)+'.'+real, {type:f.type, lastModified:f.lastModified}); + g.nomeEnviado=f.name; + return g; +} function recusa(lista){ const el=$('recusa'); if(!el) return; if(!lista.length){ el.style.display='none'; el.innerHTML=''; return; } const exts=escapeHTML([...new Set(lista.map(f=>extDe(f.name)))].join(', ')); el.style.display='block'; if(lista.every(f=>/\.jpe?g$/i.test(f.name))){ - el.innerHTML='JPG não dá para enviar. JPG não tem fundo transparente, e o branco do fundo '+ + const disfarcados=lista.filter(f=>f.nomeEnviado).map(f=>f.nomeEnviado); + el.innerHTML='JPG não dá para enviar. '+ + (disfarcados.length ? escapeHTML(disfarcados.join(', '))+' é JPG, mesmo com outro nome. ' : '')+ + 'JPG não tem fundo transparente, e o branco do fundo '+ 'sai no filme. Exporte em '+(ehFolha()?'PNG ou PDF':'PNG')+' com fundo transparente e envie de novo.'; return; } @@ -39,8 +64,9 @@ async function marcaResiduos(x){ const marcada=await previaMarcada(x.previewSrc, x.an.pontos); if(folhas.includes(x)){ x.previewSrc=marcada; pintaFolha(); } } -function sel(fs){ +async function sel(fs){ if(!fs.length) return; + fs=await Promise.all(fs.map(nomeReal)); // Pixels cannot tell a loose artwork from a finished sheet, so the customer // declares it by choosing the product in the selector above. The declaration is // verified in medirFolha; the file never changes product or price on its own.