feat: accept payment notifications, once, from a verified sender

There was no inbound payment path at all: a button called a fake synchronously
and wrote an order. A real provider does the opposite — it charges, then tells
us, repeatedly, out of order, and sometimes long afterwards.

POST /api/payments/webhook verifies the signature before the body is parsed, so
an unsigned or tampered delivery is refused and recorded without touching an
order. Verified deliveries are stored under the provider's own event id with a
unique constraint, and applied inside the same transaction that marks them
processed: a repeat is a no-op, a crash is retried rather than half-applied.

An approval whose amount disagrees with the reviewed quote does not become an
order. Underpayment would ship artwork nobody paid for, and overpayment means
something a person should look at.

Order creation moved to app/payments.py so the webhook and the local development
checkout share one implementation and cannot drift. That also closes 3.5: the
charge happens inside the transaction that persists the order, rather than
before it.

The adapter contract is create/verify/parse. FakePayment implements it with a
real HMAC scheme so the whole path is exercised now, by tests/payment_test.py:
unsigned, tampered, underpaid, duplicate, re-sent, unknown reference, and
non-approved statuses. Connecting Mercado Pago is one adapter; no service code
changes.

PAYMENT_WEBHOOK_SECRET is optional in production on purpose. Required would
break the next Portainer render, and a guessable default would be worse than
either: with no secret configured the adapter verifies nothing and therefore
accepts nothing, which is the right state until a provider is connected.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-09-22 13:25:08 -03:00
parent 7386469404
commit ccc25a2d5d
12 changed files with 537 additions and 35 deletions

144
docs/REVIEW-2026-09-21.md Normal file
View File

@@ -0,0 +1,144 @@
**DTF project review — September 21, 2026**
Reviewed revision: `7386469`. Commit window: September 21, 00:00–24:00, America/Sao_Paulo; 26 commits. This is a review, not an implementation change or production approval.
**Assessment**
The project has a useful local workflow and several sound controls, but it is not yet the automated ordering and production system described in the meeting. The largest risks are incomplete commercial integrations, loss of production instructions between the editor and API, incorrect cart/quote behavior, an upload limit that the scanner cannot support, and operational controls that are documented more strongly than they are implemented.
Today's restructuring improved navigation through the repository, but introduced broken operational entrypoints. Today's board limit also introduced a starvation bug. Passing the existing tests does not establish that the requested artwork can be reproduced correctly or that the production deployment is recoverable.
**Business baseline and scope**
I read [the September 9 meeting notes](/home/farelos/compor/dtf-sistema/docs/reuniao-2026-09-09-anotacoes.pdf) first, then compared the implementation with [the later project context](/home/farelos/compor/dtf-sistema/docs/CONTEXT.md:20) and [the client roadmap](/home/farelos/compor/dtf-sistema/docs/roadmap-cliente.pdf).
The meeting's core outcome is unattended order intake and payment, fewer designer handoffs, reliable large-file handling, a traceable queue, and separation of ready artwork from artwork needing assistance. Later decisions explicitly defer automatic print preflight, factory agents, FlexiPRINT integration, machine dashboards, and advanced reports. Their absence is not reported here as an accidental regression. The approved site pricing also supersedes the meeting's simplified 20% discount description; changing those prices would require a separate business decision.
The active layout is `web/` for browser code; `app/api/` for HTTP routes; `app/core/` for shared foundations; the remaining `app/` modules for storage, artwork, scanning, initialization, and background work; `infra/` for local images and configuration; `deploy/`, the root Swarm composition, and `.gitea/` for delivery; `ops/` for operational commands; and `tests/` for checks. Historical documents describe earlier models and should not define current acceptance criteria.
**Evidence and limits**
- Inspected the active first-party application, browser logic, schema, deployment definitions, operational scripts, tests, project documents, and today's commit history and relevant diffs. Vendored PDF.js was checked as a third-party dependency, not subjected to a line-by-line audit of its minified implementation. Historical material was used as background.
- Ran the current fast suite: 29 tests executed, 28 passed, one skipped because it still looks for the deleted `deploy/stack.yaml`.
- Parsed all first-party Python files and checked the syntax of all first-party browser JavaScript files successfully.
- Ran the isolated artwork browser suite with additional review probes against synthetic files. The existing checks passed; the probes reproduced findings 6, 7, and 10 below.
- Ran the production source preflight: it correctly reported the fake payment and messaging adapters as blockers. CI does not enforce that result by default.
- Used read-only checks in the running local API container: `ops` is absent, `app.staging_readiness` is absent, a 128 MiB + 1 byte scan is rejected, and ClamAV reports `1.5.4/28122/Sun Sep 13 06:26:25 2026`.
- Executed the actual `submit_files` function body against an in-memory connection double to confirm which file kinds it invalidates. Also reproduced the board query's 101st-quote omission against synthetic SQL data. These are targeted logic checks, not production database tests.
- Did not change application code, production services, credentials, orders, or stored artwork. Did not rerun the full container integration suite, perform a current Trivy audit, test provider sandboxes, or inspect production firewall/Portainer settings. Deployment-dependent risks below are explicitly qualified.
P1 means a delivery blocker or a material correctness, security, or recovery risk that should be resolved before accepting real customer work. P2 means an important correctness, reliability, or maintenance issue. A finding labelled a gap or design risk is not presented as an observed production incident.
**Commercial flow and artwork correctness**
1. **P1 — Production cannot complete an order. Confirmed delivery gap.** `dev-paid` returns 503 outside local mode, while runtime configuration requires fake payment, freight, Tiny, and WhatsApp adapters. There is no real payment creation/webhook/reconciliation flow, carrier quote, ERP order, or notification delivery. R2 connectivity and a healthy public page therefore do not establish a usable sales system. Complete the provider contracts and implement their sandbox-tested flows before treating the deployment as live commerce. Evidence: [orders.py:17](/home/farelos/compor/dtf-sistema/app/api/orders.py:17), [adapters.py:9](/home/farelos/compor/dtf-sistema/app/adapters.py:9), [runtime.py:24](/home/farelos/compor/dtf-sistema/app/runtime.py:24).
2. **P1 — The customer's production instructions disappear at checkout. Confirmed defect.** The editor records width, copies, rotation, mirroring, and ready-sheet repetitions, but `itemAtual` retains only totals and original Files. The API receives only mode, aggregate metres, grade, and upload IDs. It cannot tell the factory whether one artwork should be printed six times at 20 cm or with a different combination producing the same length. Neither the saved cart nor the order contains the full reproducible layout. Persist a versioned per-file production specification and the approved layout/revision. Evidence: [site-cart.js:65](/home/farelos/compor/dtf-sistema/web/site-cart.js:65), [checkout.js:65](/home/farelos/compor/dtf-sistema/web/checkout.js:65), [models.py:59](/home/farelos/compor/dtf-sistema/app/core/models.py:59).
3. **P1 — The 5 GiB upload path cannot deliver files above 128 MiB. Reproduced.** The browser/API accept 5 GiB, but `ClamAV.scan` hard-caps acceptance at `min(128 MiB, SCAN_MAX_BYTES)`, and ClamAV has matching limits. Raising the environment variable alone cannot fix it. Oversized files are rejected, blocked from quote/download/production, and scheduled for deletion; the customer may upload gigabytes before discovering this. Expose the usable limit before transfer and implement a deliberate large-file scan/release design. Evidence: [scanning.py:32](/home/farelos/compor/dtf-sistema/app/scanning.py:32), [clamd.conf:8](/home/farelos/compor/dtf-sistema/infra/clamd.conf:8), [docker-compose.yml:31](/home/farelos/compor/dtf-sistema/docker-compose.yml:31).
4. **P1 — The oldest 100 unpaid quotes can permanently hide new work. Introduced today in `543a9a9`.** The board selects the oldest unpaid quotes with a limit, including approved, expired, and abandoned quotes. There is no pagination, archive/cancel action, or pending-quote expiry that frees this window. Approved quotes are immutable, and expired ones cannot be paid, so old entries can remain indefinitely. Quote 101 is invisible even while needing review. Finished-order trimming also has no operator search/archive view for older completed work. Paginate/search history and give quotes an explicit lifecycle; do not silently cap actionable work. Evidence: [operator.py:59](/home/farelos/compor/dtf-sistema/app/api/operator.py:59), [kanban.js:24](/home/farelos/compor/dtf-sistema/web/kanban.js:24).
5. **P1 — A new correction can leave an obsolete final approved. Targeted logic reproduction.** An operator may submit finals while the order is in `cor`. The customer may then submit another correction using the latest version. `submit_files` deactivates only files of the incoming kind, so the earlier final remains active. Moving `cor → tra → fil` checks final coverage, not whether those finals were approved after the latest correction, and can accept the stale set. Invalidate finals on every accepted customer correction, or bind final approval to the specific correction revision. Evidence: [artwork.py:15](/home/farelos/compor/dtf-sistema/app/artwork.py:15), [artwork.py:40](/home/farelos/compor/dtf-sistema/app/artwork.py:40), [operator.py:118](/home/farelos/compor/dtf-sistema/app/api/operator.py:118).
6. **P2 — The stated DPI rejection and customer acknowledgement do not gate checkout. Browser-reproduced.** With 25.4-DPI artwork, the quality button was disabled but the payment button remained enabled and a cart item existed. `pintaEntrega` checks only customer data and freight; `dtfCheckout` does not check the resolution gate. The warning acknowledgement is also never recorded in the order. Manual operator review currently provides a later checkpoint, but the UI's claim that these files cannot proceed is false. Use one eligibility state for cart submission and retain any required acknowledgement against the artwork revision. Evidence: [site-quality.js:158](/home/farelos/compor/dtf-sistema/web/site-quality.js:158), [site-flow.js:90](/home/farelos/compor/dtf-sistema/web/site-flow.js:90), [checkout.js:49](/home/farelos/compor/dtf-sistema/web/checkout.js:49).
7. **P1 — Removing artwork can leave it in the submitted cart. Browser-reproduced.** After deleting the only artwork, `artes.length` became zero while `itemAtual.localFiles` still contained the removed file and checkout stayed enabled. An incomplete evaluation hides panels without clearing `itemAtual`; other invalid edits can similarly leave old totals and Files alive. Clear or invalidate the current cart item immediately whenever its underlying artwork becomes incomplete. Evidence: [site-cart.js:7](/home/farelos/compor/dtf-sistema/web/site-cart.js:7), [site-quality.js:79](/home/farelos/compor/dtf-sistema/web/site-quality.js:79), [site-pdf.js:348](/home/farelos/compor/dtf-sistema/web/site-pdf.js:348).
8. **P1 — Editing the cart after requesting a quote can still purchase the old quote. Confirmed control-flow defect.** Once `draftId` exists, checkout returns early through `refresh()` and never compares the current cart with the stored quote. The editor remains usable. The confirmation displays a server total but no full immutable item comparison, so quantity/artwork edits can be silently ignored, especially when the one-metre minimum keeps the total unchanged. Bind the UI to the quoted snapshot and explicitly replace the quote on edits. Evidence: [checkout.js:51](/home/farelos/compor/dtf-sistema/web/checkout.js:51), [checkout.js:89](/home/farelos/compor/dtf-sistema/web/checkout.js:89).
9. **P2 — PDF quantity and geometry are not reliably measured. Confirmed algorithm limitation.** Measurement searches the first/last 4 MiB for the first textual `MediaBox` and an unrelated first `UserUnit`; rendering/quality checks only page 1. There is no multi-page rejection or sum across pages. A multi-page print file can therefore be quoted as one page. Compressed/inherited page dictionaries, rotation, and page-specific units are not handled by this textual search. Use the PDF parser's page model, and either support every page or explicitly reject unsupported documents. Evidence: [site-pdf.js:101](/home/farelos/compor/dtf-sistema/web/site-pdf.js:101), [site-pdf.js:132](/home/farelos/compor/dtf-sistema/web/site-pdf.js:132).
10. **P2 — Quality grades can be based on missing or incorrect evidence. Partly browser-reproduced.** A CDR with no analysis plus an analysed PNG received grade 50 and R$18.70/m for the entire item rather than the CDR's stated table rate of R$19.90/m. `filter(Boolean)` removes unanalysed files from grading while their metres remain billable. For loose artwork, failed image decoding leaves a pixel estimate derived from compressed file size. Rotation retains the original width for DPI even when the physical width now corresponds to image height. The PDF image walker also treats no recognized images as vector artwork, although unsupported image operators or failed object lookup can yield the same result. Track quality per source and fail explicitly when measurement is unknown. Evidence: [site-quality.js:19](/home/farelos/compor/dtf-sistema/web/site-quality.js:19), [site-config.js:107](/home/farelos/compor/dtf-sistema/web/site-config.js:107), [site-upload.js:96](/home/farelos/compor/dtf-sistema/web/site-upload.js:96), [site-pdf.js:46](/home/farelos/compor/dtf-sistema/web/site-pdf.js:46).
11. **P2 — Oversized artwork is silently shrunk by the packer. Confirmed code path.** Width inputs advertise a maximum, but their JavaScript handlers accept larger values without validating form constraints. When no orientation fits, `encaixar` scales the artwork down to film width. The requested dimension and actual preview geometry then disagree, without an explicit approval to resize. Reject impossible dimensions or offer a visible, accepted resize. Evidence: [site-pdf.js:349](/home/farelos/compor/dtf-sistema/web/site-pdf.js:349), [site-packing.js:175](/home/farelos/compor/dtf-sistema/web/site-packing.js:175).
12. **P2 — The browser processing path is not bounded for large artwork. Confirmed design risk.** Images are loaded as full data URLs and decoded repeatedly; PDFs use full-file `arrayBuffer`; copy count has no effective upper bound before `Array.from`; preview canvas height grows with the whole layout. PDF timeouts race a promise without cancelling parsing/rendering or destroying the document. Large files or copy counts can exhaust memory or freeze the main thread before resumable upload helps. Bound work, avoid repeated full decodes, tile previews, cancel obsolete parsing, and provide a path that does not require browser rasterization of huge files. Evidence: [site-packing.js:6](/home/farelos/compor/dtf-sistema/web/site-packing.js:6), [site-packing.js:204](/home/farelos/compor/dtf-sistema/web/site-packing.js:204), [site-pdf.js:97](/home/farelos/compor/dtf-sistema/web/site-pdf.js:97).
13. **P1 — Home-delivery orders cannot capture a deliverable address. Confirmed MVP gap.** Customer data contains CNPJ, phone, and email; freight contains only service and CEP. There is no recipient name, street, number, complement, city/state, or validated delivery snapshot. A CEP can support an estimate, but it does not identify the destination needed to fulfil the order. Add the delivery contract together with freight integration; automated label purchase can remain out of scope. Evidence: [models.py:10](/home/farelos/compor/dtf-sistema/app/core/models.py:10), [models.py:43](/home/farelos/compor/dtf-sistema/app/core/models.py:43), [index.html:1209](/home/farelos/compor/dtf-sistema/web/index.html:1209).
14. **P1 — Unattended sales still depend on a human commercial review. Product decision outstanding.** Server pricing safely recalculates prices, but metres and grade become trusted only when an operator approves every quote. This intentionally protects the local prototype; it does not solve the meeting's after-hours bottleneck. Decide which orders can be accepted automatically, what evidence supports their price, and what exceptions require a person. Automatic print preflight being deferred does not itself settle the pricing-authority question. Evidence: [orders.py:28](/home/farelos/compor/dtf-sistema/app/api/orders.py:28), [operator.py:78](/home/farelos/compor/dtf-sistema/app/api/operator.py:78), [CONTEXT.md:262](/home/farelos/compor/dtf-sistema/docs/CONTEXT.md:262).
15. **P1 — Final print-file generation remains missing from the promised delivery. Confirmed gap.** The server stores originals and manually uploaded finals; it never generates the layout shown in the browser, applies repetitions, splits output, or adds the promised order identification. Consequently the factory must reconstruct the job, and billed metres have no machine-verifiable connection to produced metres. The client roadmap includes final-file generation in week 2 even while deferring automatic preflight. Implement a reproducible output path and print acceptance checks, or explicitly renegotiate that deliverable and the site's promises. Evidence: [api/artwork.py:45](/home/farelos/compor/dtf-sistema/app/api/artwork.py:45), [site-packing.js:342](/home/farelos/compor/dtf-sistema/web/site-packing.js:342), [ROADMAP.md:171](/home/farelos/compor/dtf-sistema/docs/ROADMAP.md:171).
**Security and access**
16. **P1 — Anonymous reservations can exhaust the entire storage quota without uploading bytes. Confirmed arithmetic/control-flow risk; no attack run.** Quota accounting immediately reserves the declared file size. With current defaults, five guest identities can reserve two 5 GiB uploads each and occupy the global 50 GiB allowance. Guest sessions and per-owner limits do not prevent this; all reservations remain until incomplete-upload cleanup after one day, and no customer abort endpoint releases them. Add global admission safeguards, short idle reservation leases, explicit cancellation, and a suitable identity/abuse policy. Evidence: [uploads.py:21](/home/farelos/compor/dtf-sistema/app/api/uploads.py:21), [health.py:26](/home/farelos/compor/dtf-sistema/app/api/health.py:26), [worker.py:21](/home/farelos/compor/dtf-sistema/app/worker.py:21).
17. **P1 — Malware signatures are already stale in the inspected local runtime. Reproduced operational gap.** The scanner runs `clamd` directly from a pinned image on an internal network, with no updater or scheduled replacement. It reports September 13 signatures on September 21, exceeding the repository's own seven-day threshold. Worker health only requires a live thread and PING. A running scanner is therefore reported healthy despite stale detection data. Establish controlled signature updates and make signature freshness visible to operations. [ClamAV's signature-management documentation](https://docs.clamav.net/manual/Usage/SignatureManagement.html) describes the update mechanism. Evidence: [docker-compose.yml:79](/home/farelos/compor/dtf-sistema/docker-compose.yml:79), [worker.py:60](/home/farelos/compor/dtf-sistema/app/worker.py:60), [security_status.py:7](/home/farelos/compor/dtf-sistema/ops/security_status.py:7).
18. **P1 — The reverse-proxy trust boundary is broader than the claimed protection. Deployment-dependent security risk introduced in `3b92813`.** Nginx accepts forwarded client addresses from every RFC1918 network, rather than the actual trusted proxy. Any reachable private peer can supply that header. The web ports use Swarm ingress, so the assumption that a direct internet request necessarily arrives with a public socket peer also needs topology testing. If untrusted traffic arrives through a trusted internal peer, it can spoof audit addresses and rate-limit buckets. Restrict trusted proxy hops and firewall the origin ports; verify through the actual Swarm/reverse-proxy chain. I did not verify production exposure or demonstrate a public exploit. Evidence: [nginx.conf.template:17](/home/farelos/compor/dtf-sistema/deploy/nginx.conf.template:17), [docker-compose.yml:143](/home/farelos/compor/dtf-sistema/docker-compose.yml:143). References: [Nginx real-IP trust](https://nginx.org/en/docs/http/ngx_http_realip_module.html), [Docker ingress routing](https://docs.docker.com/engine/swarm/ingress/).
19. **P2 — Production credentials remain plain service environment values. Confirmed configuration risk.** The actual stack supplies DB, R2, and operator secrets directly, despite the new secret-file loader and documentation describing external secrets. API and worker both receive the bootstrap operator password even though runtime authentication now uses the database. Removing the unused second stack reduced drift, but did not remove this exposure from the active one. Use the implemented file loader in the real stack and restrict each service to the secrets it needs. This is metadata/operational exposure, not evidence of a public credential leak. Evidence: [docker-compose.yml:3](/home/farelos/compor/dtf-sistema/docker-compose.yml:3), [core/secrets.py:1](/home/farelos/compor/dtf-sistema/app/core/secrets.py:1).
20. **P2 — Operator disable can race with login. Introduced with accounts in `a874033`; static concurrency finding.** Login reads the active account, performs expensive password verification, then inserts a session in a separate transaction without rechecking `active`. Disabling between those steps deletes existing sessions, but the in-flight login can create a new one afterwards. The request guard checks only session existence/expiry, so that session can authorize a disabled account for eight hours. Recheck active status atomically when issuing sessions and in authorization. Password changes also intentionally retain current sessions; document or revise that recovery policy. Evidence: [operator.py:23](/home/farelos/compor/dtf-sistema/app/api/operator.py:23), [auth.py:102](/home/farelos/compor/dtf-sistema/app/core/auth.py:102), [operators.py:80](/home/farelos/compor/dtf-sistema/app/operators.py:80).
21. **P2 — Account recovery and guest continuity are incomplete. Confirmed gap.** There is no email verification, password recovery/change flow for customers, or durable guest recovery mechanism. A guest who loses the cookie or passes its seven-day expiry cannot prove ownership merely by knowing the order/CNPJ, correctly, but also has no supported way to regain access. The site incorrectly promises account creation at payment; the order route creates no account. Complete the identity/recovery journey without weakening the existing ownership checks. Evidence: [customer.py:25](/home/farelos/compor/dtf-sistema/app/api/customer.py:25), [auth.py:58](/home/farelos/compor/dtf-sistema/app/core/auth.py:58), [index.html:1190](/home/farelos/compor/dtf-sistema/web/index.html:1190).
22. **P2 — Personal-data lifecycle is undefined beyond artwork cleanup. Confirmed governance gap, not a legal conclusion.** Profiles, quote drafts, immutable order snapshots, and integration payloads duplicate contact data without an implemented deletion/anonymization/export policy. Artwork expiry does not cover those records or retained backups. The site does link an external privacy/terms page, so claiming there is no privacy link would be inaccurate; this review did not establish whether that notice covers this processing. Define retention and access requirements for each data class, then implement them consistently. Evidence: [schema.sql:9](/home/farelos/compor/dtf-sistema/app/schema.sql:9), [schema.sql:28](/home/farelos/compor/dtf-sistema/app/schema.sql:28), [index.html:1358](/home/farelos/compor/dtf-sistema/web/index.html:1358).
**Operations and release engineering**
23. **P1 — Today's directory move broke staging, backup, and security operations. Reproduced packaging failure in `b329f76`.** Staging runs `app.staging_readiness`, but the module now lives under `ops`. Neither API Dockerfile copies `ops`. Backup still calls `local.storage_backup` inside the API container and selects plain `docker compose`, which now means the production-oriented root file rather than `compose.local.yaml`. Documentation calls nonexistent `app.backup` and `app.security_status`. These are broken operational commands, not merely stale comments. Package a deliberate operational runtime, update every executable entrypoint, and smoke-test the shipped commands. Evidence: [compose.staging.yaml:11](/home/farelos/compor/dtf-sistema/compose.staging.yaml:11), [infra/Dockerfile:10](/home/farelos/compor/dtf-sistema/infra/Dockerfile:10), [backup.py:13](/home/farelos/compor/dtf-sistema/ops/backup.py:13), [backup.py:41](/home/farelos/compor/dtf-sistema/ops/backup.py:41).
24. **P1 — PostgreSQL has no Swarm data-placement contract. Conditional recovery risk.** The active stack uses a normal local named volume with no node constraint. On a multi-node Swarm, rescheduling can attach a same-named empty local volume on another node rather than the existing database. The documented `POSTGRES_VOLUME` and `dtf_database=true` placement contract is not implemented. A single-node VPS is also a single failure domain. Specify and test persistence, placement, and recovery instead of relying on the volume name alone. Evidence: [docker-compose.yml:40](/home/farelos/compor/dtf-sistema/docker-compose.yml:40), [docker-compose.yml:180](/home/farelos/compor/dtf-sistema/docker-compose.yml:180), [PORTAINER.md:73](/home/farelos/compor/dtf-sistema/docs/PORTAINER.md:73).
25. **P1 — `latest` is published before the release scan, and deployment is not tied to the scanned pair. Confirmed pipeline design defect.** API and web `latest` tags are pushed independently before vulnerability checks. A failed scan leaves the mutable deployment tags pointing at rejected images; a manual redeploy or another run can consume them. Concurrent runs can also overwrite each other's API/web tags, while the webhook carries no exact release identity. Build and scan first, then promote one immutable API/web release and deploy that release. Evidence: [deploy.yml:194](/home/farelos/compor/dtf-sistema/.gitea/workflows/deploy.yml:194), [deploy.yml:217](/home/farelos/compor/dtf-sistema/.gitea/workflows/deploy.yml:217), [deploy.yml:243](/home/farelos/compor/dtf-sistema/.gitea/workflows/deploy.yml:243).
26. **P1 — The production gate does not validate the deployed contract. Confirmed gap.** CI runs only `--source-only`, treats failure as advisory by default, and never validates the actual Portainer metadata or observes deployment convergence. Full config validation expects names/secrets/volumes from the removed stack, while the active stack uses different variables. Positive secret-loader checks also derive their cases from that deleted file, leaving the set empty; the associated unit test skips. The two remaining provider checks match literal source strings, not working provider behavior. Retarget validation to the actual deployment, retain positive loader tests independently of a file's existence, and add release acceptance against real capabilities. Evidence: [deploy.yml:155](/home/farelos/compor/dtf-sistema/.gitea/workflows/deploy.yml:155), [production_preflight.py:17](/home/farelos/compor/dtf-sistema/deploy/production_preflight.py:17), [production_preflight.py:81](/home/farelos/compor/dtf-sistema/deploy/production_preflight.py:81), [test_secrets.py:75](/home/farelos/compor/dtf-sistema/tests/test_secrets.py:75).
27. **P1 — Browser tests can be skipped on a green release, and their upload endpoint is incompatible with the runner topology. Confirmed CI gap.** Missing Chrome or inaccessible host loopback returns success. Meanwhile CI signs browser storage URLs for `http://storage:9000`, a Compose-only hostname; installing Chrome or making host ports reachable does not by itself give that browser access to storage. These are the only broad tests of the artwork/cart journey. Run Chrome and the tests in a compatible network, then make omission fail the release. Evidence: [deploy.yml:45](/home/farelos/compor/dtf-sistema/.gitea/workflows/deploy.yml:45), [deploy.yml:90](/home/farelos/compor/dtf-sistema/.gitea/workflows/deploy.yml:90), [browser_test.mjs:44](/home/farelos/compor/dtf-sistema/tests/browser_test.mjs:44).
28. **P2 — CI runs share fixed ports and lack enforced project isolation. Conditional concurrency risk.** The integration job uses the same five host ports, relies on the default Compose project name, and ends with `down -v`. Overlapping runs on the shared Docker daemon can collide; if their project names coincide, they can also operate on each other's containers and volumes. Selecting currently unused ports fixed one collision but not concurrency. Allocate a unique project/network per run, avoid unnecessary published ports, and serialize release promotion. Evidence: [deploy.yml:27](/home/farelos/compor/dtf-sistema/.gitea/workflows/deploy.yml:27), [deploy.yml:121](/home/farelos/compor/dtf-sistema/.gitea/workflows/deploy.yml:121).
29. **P1 — Health checks do not establish operational readiness or successful delivery. Confirmed monitoring gap.** Public `/health` always returns 200 from Nginx. API health checks DB/storage, while worker health can remain green during repeated provider failures, stale signatures, or failed cleanup. `last_tick` advances even after a delivery retry is scheduled. Cleanup handles a batch in one transaction; one consistently failing object can roll back progress and repeatedly block later expired objects. There is no implemented external alert routing or post-webhook application verification, and the stack lacks explicit rollback/update policies described in the docs. Separate liveness from readiness and alert on backlog age, cleanup progress, signatures, backup age, and deployment acceptance. Evidence: [nginx.conf.template:32](/home/farelos/compor/dtf-sistema/deploy/nginx.conf.template:32), [worker.py:21](/home/farelos/compor/dtf-sistema/app/worker.py:21), [worker.py:35](/home/farelos/compor/dtf-sistema/app/worker.py:35), [deploy.yml:243](/home/farelos/compor/dtf-sistema/.gitea/workflows/deploy.yml:243).
30. **P1 — Recoverability is not implemented as a production service. Confirmed gap beyond the broken commands.** There is no scheduled offsite encrypted backup, production restoration procedure, or tested recovery objective. The local backup dumps PostgreSQL and selects object bytes afterwards, without a shared snapshot or enforced pause; concurrent uploads/retention can produce mismatched state. Its restore check validates database counts and archived bytes separately, not that every required live order file is restorable. Define a consistent recovery boundary, required data classes, backup retention, and a rehearsed restoration procedure. Evidence: [backup.py:27](/home/farelos/compor/dtf-sistema/ops/backup.py:27), [storage_backup.py:46](/home/farelos/compor/dtf-sistema/ops/storage_backup.py:46), [LOCAL_SETUP.md:216](/home/farelos/compor/dtf-sistema/docs/LOCAL_SETUP.md:216).
31. **P1 — Real payment and integration failure semantics are not yet represented. Design gap before enabling providers.** The mock payment is called before the order transaction commits. A future provider success followed by a DB failure needs a durable payment intent, provider idempotency, and reconciliation. The outbox has a useful unique event key, but retries can let a later event for the same order overtake an earlier failed event; permanent failures retry forever without a dead-letter/operator resolution path. Provider-side success followed by a crash can also repeat delivery. There are no real pending/failed/refunded/cancelled payment states or corresponding production rules. Implement those contracts before substituting real network calls for fakes. Evidence: [orders.py:34](/home/farelos/compor/dtf-sistema/app/api/orders.py:34), [worker.py:35](/home/farelos/compor/dtf-sistema/app/worker.py:35), [runtime.py:43](/home/farelos/compor/dtf-sistema/app/runtime.py:43).
32. **P2 — Upload/scanning throughput and timeout behavior are poorly matched. Confirmed design limitation.** Files and their 8 MiB parts are uploaded sequentially, with one API presign round-trip per part; the browser then waits for scanning before uploading the next file. One scan thread handles all work, holds a DB transaction during the remote read/scan, and the browser gives up after roughly 150 polls. Scanner errors shorten retention to three days even if a later retry succeeds; success does not restore that deadline. Add bounded transfer concurrency, separate upload completion from scan waiting, measure queue latency, and distinguish transient scanner faults from rejected content. Evidence: [upload.js:9](/home/farelos/compor/dtf-sistema/web/upload.js:9), [checkout.js:60](/home/farelos/compor/dtf-sistema/web/checkout.js:60), [scanning.py:55](/home/farelos/compor/dtf-sistema/app/scanning.py:55).
**Architecture, verification, and maintenance**
33. **P2 — Database integrity and schema evolution rely too heavily on application convention. Confirmed design weakness.** Startup replays one growing SQL script without a general ordered migration/version contract. Orders reference artwork inside JSON instead of relational order-item/upload references; states and scan states lack checks, and upload expiry remains nullable. The database cannot enforce several invariants that the application assumes. Today's index-before-table regression, fixed in `86b8199`, demonstrates why clean initialization and upgrade paths both need testing. Use versioned migrations, explicit core relationships/constraints, and verify supported upgrades as well as empty installations. Evidence: [bootstrap.py:29](/home/farelos/compor/dtf-sistema/app/bootstrap.py:29), [schema.sql:14](/home/farelos/compor/dtf-sistema/app/schema.sql:14), [schema.sql:71](/home/farelos/compor/dtf-sistema/app/schema.sql:71).
34. **P2 — File separation has not yet produced clear internal boundaries. Confirmed maintenance risk.** The browser scripts share mutable globals and a required evaluation order; cart and editor state can diverge, as reproduced above. API routes still implement SQL/business transactions, and the operator artwork router imports and calls the customer upload route functions directly. `runtime.py` constructs environment-bound adapters at import time, making isolated business tests harder. Every database operation creates a new connection, and synchronous audit DB writes also run directly in async middleware. Keep the small deployment, but move reusable use cases behind explicit interfaces, use one cart state model, and introduce bounded connection management as load requires. Evidence: [index.html:1376](/home/farelos/compor/dtf-sistema/web/index.html:1376), [api/artwork.py:15](/home/farelos/compor/dtf-sistema/app/api/artwork.py:15), [runtime.py:21](/home/farelos/compor/dtf-sistema/app/runtime.py:21), [db.py:6](/home/farelos/compor/dtf-sistema/app/core/db.py:6), [app.py:30](/home/farelos/compor/dtf-sistema/app/app.py:30).
35. **P2 — Existing tests verify the mock workflow more strongly than the delivered product. Confirmed coverage gap.** Pricing parity is valuable, but uses only 11 lengths and shared tables; it cannot validate print geometry. Integration fixtures deliberately use plain text with a `.cdr` extension, which tests transport but proves no printability. The current isolated browser server does not serve `/vendor/...`, and its tests do not exercise real PDF parsing. Missing operational entrypoints and stale-cart behavior passed the suite. CI tests local images/configuration, not the final production images and Swarm proxy topology. Add targeted acceptance for the defects above, real representative artwork, fault/retry cases, clean/upgrade schema paths, operational command packaging, and the exact release artifacts. Evidence: [test_pricing.py:10](/home/farelos/compor/dtf-sistema/tests/test_pricing.py:10), [fixtures/local-test.cdr](/home/farelos/compor/dtf-sistema/tests/fixtures/local-test.cdr), [artwork_browser_test.mjs:26](/home/farelos/compor/dtf-sistema/tests/artwork_browser_test.mjs:26), [deploy.yml:59](/home/farelos/compor/dtf-sistema/.gitea/workflows/deploy.yml:59).
36. **P2 — Documentation and generated deliverables can send operators to the wrong system. Partly introduced today.** README's active quick start still selects the production Compose file. Portainer instructions tell users to populate secret/volume/host variables the actual stack does not consume. Security/context documents still claim absent rollback, secrets, blocked deployment, or obsolete CDN behavior. The historical index calls the local milestone report a different prototype. The client PDF's diagram still labels a worker preflight while its scope defers it. Moving the PDF generator in `66ddb17` left `parents[2]`, which now resolves to `/home/farelos/compor`, outside this repository, and its output path no longer matches the documented PDF. Correct executable instructions and current claims, and validate generated output paths. Evidence: [README.md:3](/home/farelos/compor/dtf-sistema/README.md:3), [PORTAINER.md:73](/home/farelos/compor/dtf-sistema/docs/PORTAINER.md:73), [SECURITY_REPORT.md:40](/home/farelos/compor/dtf-sistema/docs/SECURITY_REPORT.md:40), [generate_dtf_report.py:17](/home/farelos/compor/dtf-sistema/tools/generate_dtf_report.py:17).
37. **P2 — Dependency/rebuild claims exceed the enforced supply-chain contract. Confirmed maintenance gap.** Vendoring PDF.js removed the CDN dependency, but version 3.11.174 remains old and has no automated inventory/update check. Its known eval advisory is mitigated by the existing `isEvalSupported:false` and restrictive CSP; this is not reported as demonstrated arbitrary code execution. PostgreSQL remains a mutable tag; CI scans only the application images. Unversioned OS upgrades and optional base-image overrides also mean a pinned base alone does not guarantee identical rebuilt images. The pricing tables are still separately maintained in JS/Python, though parity tests help. Record complete dependency provenance, scan all deployed images and vendored assets, and maintain a controlled refresh process. Evidence: [vendor/README.md:7](/home/farelos/compor/dtf-sistema/web/vendor/README.md:7), [site-pdf.js:97](/home/farelos/compor/dtf-sistema/web/site-pdf.js:97), [docker-compose.yml:41](/home/farelos/compor/dtf-sistema/docker-compose.yml:41), [deploy/Dockerfile.api:16](/home/farelos/compor/dtf-sistema/deploy/Dockerfile.api:16). Reference: [Mozilla's advisory and workaround](https://github.com/mozilla/pdf.js/security/advisories/GHSA-wgrm-67xf-hhpq). No fresh vulnerability counts are asserted here.
**Today's commit assessment**
| Commits | Result at reviewed HEAD |
|---|---|
| `341f154`, `d2f7b2c` | Secret-file loader and tests are useful; active stack still does not use them. |
| `9da2a7d`, `bbcc8ab` | Added real gates, but source readiness remains advisory and publication precedes image acceptance. |
| `4c9fa24`, `010c2a1` | Pinned application bases and added CRITICAL scanning. Do not infer current zero findings for every deployed service. |
| `6c52ad6`, `6a50e6d` | Fixed CI image retrieval/configuration packaging. |
| `24cb52d`, `7cab210`, `c1a07a7`, `dbc9ba4` | Improved integration execution after port/network failures; browser/network coverage and run isolation remain incomplete. |
| `3b92813` | Recovered proxy client headers but trusts overly broad private ranges; needs real-topology verification. |
| `e95a42d`, `9926d3a`, `91269ce` | Removed duplicate stack definition; active hardening and documentation were not reconciled completely. |
| `da903db` | Removed PDF.js CDN dependency; old dependency and PDF logic remain. |
| `a874033` | Added useful per-operator attribution; session issuance has a disable/login race. |
| `543a9a9`, `86b8199` | Added useful indexes and bounded finished history; fixed table/index ordering. Quote truncation creates starvation. |
| `ca69843` | Removed inactive prototypes; this correctly reduces ambiguity and should not be counted as lost active functionality. |
| `96f1d27`, `c9f8122` | Improved code navigation and router assembly. Global state and business boundaries remain coupled. |
| `66ddb17` | Removed accidentally tracked deliverables from HEAD and relocated artifacts; generator root/output was not updated. Untracking does not remove historical Git objects. |
| `b329f76` | Improved directory roles; broke staging/backup/security command packaging. |
| `7386469` | Centralized engineering docs; several executable instructions and current-state claims still disagree with code. |
The overall problem with today's work is incomplete acceptance around operational entrypoints and domain behavior. The reorganizations themselves are reasonable. Neither a microservice rewrite nor returning to the deleted prototypes would address the findings above.
**Recommended order of work**
1. Fix confirmed data/work-loss defects: preserve production instructions; clear stale cart state; bind quotes to the displayed cart; remove quote starvation; invalidate finals after corrections.
2. Repair operational command packaging and establish a real backup/restore path. Address stale signatures, anonymous quota exhaustion, and the actual proxy trust boundary before accepting public uploads.
3. Resolve the two central product decisions: unattended price authority and supported large-file processing. Align the site promises with the chosen interim behavior.
4. Complete the MVP contracts: destination address/freight, durable payment intents and webhooks, Tiny, final-file generation, and the four WhatsApp events. Test their failure/reconciliation paths in staging.
5. Make release identity, exact-artifact testing, browser tests, production configuration checks, and post-deployment verification enforceable. Reconcile the documentation with that one implementation.
The current controls worth preserving are server-calculated prices, immutable approved quotes, owner-scoped access, parameterized SQL, password hashing, revocable HttpOnly sessions, strict script CSP, private signed storage access, malware quarantine, state/version checks, transactional outbox insertion, and dependency hashes. This review identifies material defects and gaps supported by the inspected code; it does not establish that every possible flaw has been found.