Saltar a contenido

Reverse-engineering snapshot of tipre/GatewayMP-JH8, generated 2026-10-01. Committed secrets were found and intentionally NOT reproduced.

Reverse-engineering report: tipre/GatewayMP-JH8 (Mercado Pago QR gateway, JHipster 8)

Source: shallow clone (depth 50) of tipre/GatewayMP-JH8. Base Java package com.tipre.gatewaymp (shortened to …/gatewaymp).

Committed secrets (treat as burned, rotate): - JWT HMAC secret in .yo-rc.json and src/main/resources/config/application-prod.yml. - Gmail SMTP app password in a comment in …/gatewaymp/service/LogErrorService.java.

1. Stack and versions

Item Value Source
Generator JHipster 8.1.0, monolith, JWT, Angular, es only, admin UI, baseName GatewayMp .yo-rc.json
Spring Boot 3.2.0 (jhipster-dependencies 8.1.0) pom.xml
Java 17; Jib base eclipse-temurin:17-jre-focal pom.xml
Hibernate 6.3.1.Final + Envers pom.xml
DB SQL Server (dev and prod), mssql-jdbc pom.xml
Migrations Liquibase 4.24.0 + liquibase-mssql; ddl-auto: none
Frontend Angular 17.0.6, ng-bootstrap 16, Bootstrap 5.3.2, Jest 29.7 package.json
Other libs org.json (hand-rolled JSON), qrgen, RestTemplate + Apache HttpClient 5, oauth2-resource-server (own JWT only), mail, springdoc
Tests JUnit 5, Spring Boot Test, ArchUnit 1.2.1, Testcontainers mssql, JaCoCo
Quality Sonar, checkstyle, Husky + lint-staged
Docker app/mssql/monitoring/sonar compose, Jib, Prometheus + Grafana src/main/docker
CI None

1233 tracked files, 191 Java files, history 2024-01-26 → 2026-04-17, 3 authors, ~45 tags.

2. Architecture

Classic JHipster layered monolith, not hexagonal. TrxResource (1042 lines) holds the whole payment orchestration. Packages: config/, domain/ (Comercio, Sucursal, Pos, Trx, Ipn, TxRx, LogError, CategoriaHorario, HorarioSucursal), domain/dto/ (Trxid, TrxRtaPos, CMHashMapResponse), domain/enumeration, repository/, service/ (TrxService, TxRxService = only MP HTTP client, IpnService, CancelacionesService, LogErrorService, GeoCodeService), web/rest/, helper/ (My* utilities, StringTruncationUtil).

Conventions: Spanish lowercase-glued field names (merchantorderid, mpexternalposid); My* helper prefix; entities exposed directly in REST; config via env.getProperty("server.mercadopago.*") instead of typed properties. ArchUnit TechnicalStructureTest is the stock JHipster layering rule.

3. POS-facing API contract

All POS endpoints are permitAll. Endpoint names are properties (server.mercadopago.pos-endpoints: trxid, trxpago, trxanulacion, trxes).

Endpoint Behaviour
POST /api/trxid {comercio, sucursal, pos}, id null. Validates enabled hierarchy, creates Trx OBTENCIONIDTRX, returns 201 Trxid {id, pos, sucursal, comercio, qrData, mpposid}
POST /api/trxpago {id, totalitem, totalcashback, nropv?, nroticketfiscal?, uniquereference?}. Synchronous, blocking: puts MP QR order, holds request polling/waiting IPN until paid or waitpago-timeout (dev 30 s, default 180 s). 200 approved, 400 timeout/cancel, 500 MP error
POST /api/trxanulacion {id} of original. Deletes pending QR order or refunds payment. Returns REFUND_*
GET /api/trxes/{id} TrxRtaPos; 400 if id ≤ 0, 404 not found
GET /api/trxes/view/{id} Full Trx entity, public (leak, see §6)
GET /api/pos/posmp, /api/pos/qrpos POS entity / QR image, URL or data
POST /api/ipn/{posexternalrefid} MP webhook, always 200

TrxRtaPos: id, merchantorderid, paymentid, estado, statuscode, total, totalitem, totalcashback, paymentmethodid, paymentmethodtype, trxfecha, message, paymentinstallments, accion, mpposid, originwalletid, payerlongname, mediodepago="MERCADOPAGO".

Retry semantics on trxpago are state-driven: PAGO_APROBADO → same response; PAGO_ENVIADO → 400 "pago en curso"; accion=CANCELAR → 400; denied/cancelled/refund → 400.

Shared POS contract with GatewayQR: only /api/trxid. Pay and annul share URL names but bodies and states differ (GatewayQR: importe, trxidoriginal, 2-phase INTENCION_DE_PAGO_*/AUTORIZACION_DE_PAGO_*; GatewayMP: totalitem/totalcashback, short state set). No canonical TrxRtaPos exists across gateways.

4. Mercado Pago integration

  • Auth: static per-merchant access token in plain text (Comercio.accesstoken), copied into every Trx row. Bearer on GET/POST, but in the URL query on PUT/DELETE (TxRxService L146-152) → leaks into logs and TxRx.url.
  • Outbound: PUT …/stores/{extStore}/pos/{extPos}/orders (external_reference = trx.id, total, notification_url, items, cash_out, sponsor); DELETE/GET same path; GET /merchant_orders/{id} and ?external_reference=; GET /v1/payments/{id} and /search; POST /v1/payments/{id}/refunds; PUT /payouts/refunds/{id}; admin-time provisioning of stores (with Google geocoding) and POS.
  • IPN: public, no signature validation, persisted in Ipn, merchant_order topic pushed into a static ConcurrentHashMap. Treated as a hint; truth comes from an MP GET.
  • Pay loop (TrxResource.postPayment): pre-delete stale order → set PAGO_ENVIADO + accion=CANCELAR as fail-safe → PUT order → loop (sleep 1 s, wait IPN ≤ 5 s, verify external_reference, check order still on QR, query paid) → on timeout re-check three ways so a last-second payment is returned as approved.
  • Timeouts/retries: connect 3 s; read timeout line commented out; new RestTemplate per call; no Resilience4j, no circuit breaker.
  • Idempotency: X-Idempotency-Key only on refunds, value {trxid}-{payload} (own TODO flags it as flawed). Orders idempotent by external_reference.
  • Cancellation sweeper (CancelacionesService): reloads accion='CANCELAR' rows into a static map at startup; @Scheduled (5 s) deletes QR order / refunds payout / refunds payment, marks REFUND_*. Retries forever (TODO "reintentar FOREVER???"). Single-instance only: no DB lease.
  • No end-of-day reconciliation.

5. Domain model and state machine

Comercio (nombre, habilitado, cuit, cbu, accesstoken, userid) 1:N Sucursal (numero, mpid, mpexternalstoreid, address, lat/long, horario) 1:N Pos (numero, mpid, mpexternalposid, mpqrimageurl, mpqrdata). Trx ~50 columns (MP ids, amounts, card/payer metadata, merchant snapshots, estado, accion, raw POS JSON), Envers-audited. Ipn, TxRx (wire log, 10,000 chars each side), LogError (can email). Latest commit adds JDL for Point terminals (Terminal, Trxpoint, TxRxPoint) with no Java yet.

StatusTypes: OBTENCIONIDTRX, PAGO_ENVIADO, PAGO_APROBADO, PAGO_DENEGADO, PAGO_CANCELADO, REFUND_APROBADO, REFUND_DENEGADO, REFUND_APROBADO_PARTIALLY. Orthogonal Acciones: CANCELAR, CANCELADO_NOEXISTE_EN_MP, CANCELADO_REFUND.

stateDiagram-v2
    [*] --> OBTENCIONIDTRX: POST /trxid
    OBTENCIONIDTRX --> PAGO_ENVIADO: POST /trxpago, order PUT ok (accion=CANCELAR as safety)
    PAGO_ENVIADO --> PAGO_APROBADO: order_status=paid (IPN hint + MP GET)
    PAGO_ENVIADO --> PAGO_ENVIADO: PUT failed or timeout, accion=CANCELAR
    PAGO_APROBADO --> REFUND_APROBADO: POST /trxanulacion, refund ok
    PAGO_APROBADO --> REFUND_APROBADO_PARTIALLY: payment refunded, payout not
    PAGO_ENVIADO --> REFUND_APROBADO: sweeper deleted order or refunded
    PAGO_ENVIADO --> REFUND_DENEGADO: payment never existed
    REFUND_APROBADO --> [*]
    REFUND_DENEGADO --> [*]
    PAGO_APROBADO --> [*]

PAGO_DENEGADO and PAGO_CANCELADO are checked but never set. accion is effectively the pending-compensation flag.

6. Cross-cutting

Security issues: 1. GET /api/trxes/view/{id} is public and returns the whole Trx including accesstoken and payer ID number; sequential ids → enumerable. 2. IPN not signed. 3. PosResource resolves sucursal by number without merchant → collisions across merchants. 4. Plain-text tokens in DB, returned by /api/comercios. 5. Token in URL query on PUT/DELETE. 6. Default JHipster SA password in dev compose.

POS endpoints have no authentication (identification by body fields); optional plain-HTTP port for legacy POS.

Observability: JHipster LoggingAspect, CRLFLogConverter, runtime log levels; Micrometer/Prometheus, Grafana compose; no business metrics, no tracing.

Audit: TxRx wire log, Ipn, Envers on Trx, LogError (+ email), StringTruncationUtil after production overflow incidents.

Admin UI (Angular): CRUD for all entities, user management, metrics/health/logs/config; creating Sucursal/Pos provisions it in MP.

Tests: 57 test files / ~277 @Test, mostly JHipster scaffold. Payment-critical code has no tests (TrxService, TxRxService, IpnService, CancelacionesService, pay loop). No WireMock/MP stubs.

Docs: stock README; JDL; TODO comments at the top of TrxResource.java are the real backlog of MP edge cases.

Schema drift: Liquibase changelogs only cover the 2024-01 generation; later columns (accesstoken, uniquereference, payoutid, Envers tables) applied by hand.

7. Ideas worth reusing / anti-patterns

Reuse: 1. Identification step then pay step; pay is idempotent by state. 2. Compensating-action flag set before the outbound call + startup reload + sweeper (move the queue to the DB). 3. Webhook as hint, provider query as truth. 4. Late-payment protection: re-check the provider before cancelling on timeout. 5. Per-call wire audit table + separate webhook table. 6. Merchant/branch/POS hierarchy in DB with enabled flags; provisioning from admin UI. 7. Deterministic refund idempotency key derived from (trx id, refund id). 8. Truncation with warning; snapshots of exact POS request/response. 9. ArchUnit, Testcontainers MSSQL, Prometheus/Grafana.

Avoid: - 1000-line controller owning orchestration; no provider port. - Blocking request sleeping up to 3 min on a platform thread. - Static in-memory maps as IPN mailbox and work queue (single node, lost on restart). - New RestTemplate per call, no read timeout, no bounded retries. - Tokens in URL, plain text, copied per row; committed secrets; entities on public endpoints. - Unauthenticated webhook and POS API. - org.json plumbing and error flags injected into JSON. - Retry-forever loops. - Two overlapping state fields; declared-but-unused states. - Incomplete migrations.