Skip to content

feat(backend): merchant onboarding validation + caching, hosted checkout caching + concurrency control (#1769, #1770, #1775, #1777) - #1915

Merged
emdevelopa merged 5 commits into
emdevelopa:mainfrom
Abidoyesimze:feature/be-merchant-checkout-hardening-1769-1770-1775-1777
Nov 23, 2026
Merged

emdevelopa merged 5 commits into
emdevelopa:mainfrom
Abidoyesimze:feature/be-merchant-checkout-hardening-1769-1770-1775-1777

Conversation

@Abidoyesimze

Copy link
Copy Markdown
Contributor

Closes #1769
Closes #1770
Closes #1775
Closes #1777

One commit per issue, plus one base fix that the merchant route tests need in order to load at all.

Base fix: Horizon client modules failed to import on main

8e375e0. Two breakages on main meant src/lib/stellar.js, and every route that imports it (including merchants.js), failed to load under vitest:

  • horizon-client/sanitizer.js: the CONTROL_CHARS_PATTERN regex contained literal U+2028/U+2029 characters, which are line terminators in JS source, so the regex literal could not be parsed. Replaced them with 

 escapes.
  • horizon-client/retry-manager.js: a merge dropped HealthStatus, HEALTH_STATE_VALUE, MAX_TRACKED_OPERATIONS, resolveUnhealthyThreshold and three metric imports, so constructing the client threw ReferenceError. Restored them from 885b3b1.

#1769: Input validation and payload sanitization (merchants.js)

  • validateMerchantRequest() keeps the existing 400 { error: "Validation failed", errors } contract. It adds merchant_payload_rejections_total{route,reason} and logs field names only, never values.
  • register-merchant:
    • The schema is now strict, so mass-assigned fields (api_key, webhook_secret, password_hash, …) return 400.
    • Emails are stored lower-cased. Before this, A@x.com and a@x.com could both register because the lock key lower-cased the email but the existence check did not.
    • Passwords are capped at 72 bytes, the length bcrypt actually hashes.
    • business_name is length-bounded and HTML-safe.
  • The credential routes (rotate-key, regenerate-webhook-secret, generate-api-key, webhook-settings/verify) take no input and now reject any body.
  • merchant-branding / preview-receipt use a strict schema. logo_url must be https: or a base64 PNG/JPEG/GIF/WebP data URI.
  • test-webhook is now sanitized, HTTPS-only and rejects embedded credentials. The receiver's echoed response body is truncated and stripped of control characters.
  • webhook-settings uses the same URL rules as test-webhook.
  • Security: renderReceiptEmail interpolated logo_url and business_name without escaping, and /preview-receipt serves that HTML as text/html, so a crafted logo_url was reflected XSS. All values are now escaped, and the logo scheme is checked again at render time, which also covers rows saved before this PR.
  • Fixed missing imports (resolveBrandingConfig, sendWebhook, getPayloadForVersion) that made GET /merchant-branding and POST /test-webhook throw ReferenceError.

#1770: Redis caching and throughput telemetry (merchants.js)

  • Read-through cache for merchant-profile, merchant-branding and webhook-settings. Only the masked webhook response is cached; raw secrets and API keys never reach Redis. api-key-status is not cached.
  • Invalidation uses a per-merchant generation counter (atomic INCR), so a reader racing a writer cannot put a stale row back. Every branding, webhook-settings, verification (including DLQ-recovered ones) and webhook-secret write invalidates.
  • Fail-open: every Redis call has a time limit (REDIS_CACHE_OP_TIMEOUT_MS). If Redis errors or is down, the request reads the database.
  • route-throughput-telemetry.js adds request counts by status class, a latency histogram and an in-flight gauge, labelled by route pattern. It only counts requests this router actually serves.
  • Cached responses carry Cache-Control: private, no-store and X-Cache.

#1775: Redis caching and throughput telemetry (paymentDetails.js)

  • Merchant-scoped cache for GET /api/payments/:id. Terminal payments are cached for 300 s, in-progress payments for 2 s (both configurable). 404s and errors are never cached.
  • invalidatePaymentCache(), which every payment writer already calls, now also bumps a per-payment generation, so a status change shows on the next poll.
  • Soft delete previously invalidated nothing. It now invalidates.
  • Adds throughput telemetry and cache-operation metrics.
  • These are the first route-level tests for paymentDetails.js.

#1777: Concurrency control and atomic handling (paymentDetails.js)

  • Merchant-scoped single flight: a burst of identical polls costs one cache read, one DB read and one Horizon call. Followers get deep copies (X-Cache: COALESCED), and a failure is never replayed to later requests.
  • Horizon enrichment runs behind a bulkhead (reusing ConcurrencyLimiter) with a response deadline. When it is saturated or slow, the payment is returned with stellar_tx: null instead of a 503.
  • Snapshot consistency: stellar_tx is attached only when Horizon's hash matches the tx_id from the same row read. The cache store is skipped if a writer invalidated during the load.
  • No response is written after the client disconnects.

Docs: backend/docs/MERCHANT_ONBOARDING_KEY_LIFECYCLE.md, backend/docs/HOSTED_CHECKOUT_SESSION_ROUTE.md. New environment variables are listed in .env.example.

Test output

Every test file added or touched by this PR, run from backend/:

$ npx vitest run <22 files below>
 ✓ src/lib/merchant-payload-validation.test.js (85 tests)
 ✓ src/lib/request-schemas.test.js (33 tests)
 ✓ src/lib/stellar/horizon-client/retry-manager.test.js (21 tests)
 ✓ src/routes/merchant-onboarding-validation.test.js (45 tests)
 ✓ src/lib/merchant-key-lifecycle.test.js (17 tests)
 ✓ src/routes/merchant-settings-validation.test.js (27 tests)
 ✓ src/routes/paymentDetails.test.js (12 tests)
 ✓ src/routes/merchant-cache.routes.test.js (11 tests)
 ✓ src/lib/payment-details-recovery.test.js (16 tests)
 ✓ src/lib/stellar/horizon-client/sanitizer.test.js (39 tests)
 ✓ src/lib/merchant-recovery.test.js (14 tests)
 ✓ src/routes/merchants.test.js (7 tests)
 ✓ src/lib/payment-details-concurrency.test.js (15 tests)
 ✓ src/lib/merchant-cache.test.js (16 tests)
 ✓ src/routes/soft-delete.test.js (9 tests)
 ✓ src/lib/payment-details-cache.test.js (19 tests)
 ✓ src/lib/email.test.js (11 tests)
 ✓ src/lib/webhook-subscriptions.test.js (17 tests)
 ✓ src/lib/redis-json-cache.test.js (10 tests)
 ✓ src/lib/payment-cache-scoping.test.js (7 tests)
 ✓ src/lib/route-throughput-telemetry.test.js (4 tests)
 ✓ src/routes/prometheus-concurrency.test.js (2 tests)
 Test Files  22 passed (22)
      Tests  437 passed (437)

Before the base fix, merchants.test.js (7 tests), merchant-settings-validation.test.js and every suite importing src/lib/stellar.js failed at import time on main.

On main the full backend suite has pre-existing failures (2,938 tests: 2,521 passed, 303 failed; 40 test files fail to load). These are integration and env-dependent suites that need a live database or Horizon, and none are touched here. A test-by-test comparison of the full suite against main will follow in a comment.

Security notes

  • Cache keys and single-flight keys always include the merchant id, and the ownership filter stays in SQL, so neither a cache hit nor a coalesced lookup can widen access ([Backend] Fix data inconsistency issue in Path Payment Service #1311 class).
  • No credentials are cached. Ids are checked against a key-safe pattern before they are used in a Redis key.
  • Metric labels use route patterns, never ids or URLs. Validation logs never include submitted values.
  • Every new failure mode (Redis down or slow, Horizon down or slow) degrades to the existing database or "no stellar_tx" behaviour, never to an error response.

- sanitizer.js: CONTROL_CHARS_PATTERN contained literal U+2028/U+2029,
  which are line terminators in JS source, so the regex literal (and every
  module importing it) failed to parse. Use \u2028\u2029 escapes.
- retry-manager.js: a merge dropped HealthStatus, HEALTH_STATE_VALUE,
  MAX_TRACKED_OPERATIONS, resolveUnhealthyThreshold and three metric
  imports, so constructing the HorizonClient threw a ReferenceError at
  import time. Restored from 885b3b1.

Together these made src/lib/stellar.js (and every route that imports it,
including merchants.js) unloadable under vitest.
…anitization in Merchant Onboarding and Key Lifecycle Route

Closes emdevelopa#1769

- validateMerchantRequest(): strict Zod validation with the existing 400
  contract, plus merchant_payload_rejections_total{route,reason} and
  value-free structured logs; sanitizer now also counts dropped keys
- register-merchant: strict schema (mass assignment -> 400), lower-cased
  emails (closes case-variant duplicate accounts), 72-byte bcrypt password
  cap, bounded business_name without HTML meta characters
- rotate-key / regenerate-webhook-secret / generate-api-key /
  webhook-settings/verify: reject any body (emptyBodySchema)
- merchant-branding / preview-receipt: strict branding schema; logo_url
  limited to https: or raster base64 data URIs
- test-webhook: sanitized, HTTPS-only, no embedded credentials, echoed
  receiver body clipped and stripped of control characters
- webhook-settings: shares the webhook URL rules
- renderReceiptEmail escapes all interpolated values (reflected/stored XSS
  via /preview-receipt) and re-checks the logo scheme
- fix missing imports (resolveBrandingConfig, sendWebhook,
  getPayloadForVersion) that made GET /merchant-branding and
  /test-webhook throw ReferenceError
- fix stale supabase mock in merchant-settings-validation.test.js that
  predates the emdevelopa#1772 compare-and-swap
- docs/MERCHANT_ONBOARDING_KEY_LIFECYCLE.md
… for Merchant Onboarding and Key Lifecycle Route

Closes emdevelopa#1770

- lib/redis-json-cache.js: fail-open JSON get/set/delete and generation
  counters with a per-operation timeout (REDIS_CACHE_OP_TIMEOUT_MS)
- lib/merchant-cache.js: read-through cache for merchant-profile,
  merchant-branding and webhook-settings (masked response only; raw
  secrets never enter Redis). Per-merchant generation counter (atomic
  INCR) so a reader racing a writer cannot re-populate a stale row
- invalidation after branding / webhook-settings / verification /
  webhook-secret writes, including DLQ-recovered verifications
- lib/route-throughput-telemetry.js: per-route request count by status
  class, latency histogram and in-flight gauge, labelled by route pattern
  and limited to requests this router actually serves
- Cache-Control: private, no-store and X-Cache on cached reads
- fake Redis helper gains INCR/EXPIRE; route tests use it so they never
  share locks or cache state with a local Redis
- docs + .env.example
… for Public Hosted Checkout Session Route

Closes emdevelopa#1775

- lib/payment-details-cache.js: merchant-scoped Redis read-through cache
  for GET /api/payments/:id with state-aware TTLs (terminal 300s, in
  progress 2s, configurable); 404s and errors never cached; fail-open
- per-payment generation counter bumped by invalidatePaymentCache(), which
  every payment writer already calls, so status changes are visible at
  once and racing readers cannot re-store a stale body
- soft delete now invalidates the payment caches (previously none)
- throughput telemetry (requests by status class, latency, in-flight) and
  cache-operation counters in the payment-details registry
- Cache-Control: private, no-store and X-Cache headers
- first route-level tests for paymentDetails.js
- docs/HOSTED_CHECKOUT_SESSION_ROUTE.md + .env.example
…dling for Public Hosted Checkout Session Route

Closes emdevelopa#1777

- lib/payment-details-concurrency.js:
  - merchant-scoped single flight: a burst of identical polls shares one
    cache read, one DB read and one Horizon call; followers get deep
    copies (X-Cache: COALESCED); failures are never replayed; bounded map
  - Horizon enrichment bulkhead (reuses ConcurrencyLimiter) with a
    response deadline; saturation/timeouts return the payment with
    stellar_tx: null instead of failing; abandoned lookups keep their slot
    until Horizon answers
  - snapshot consistency: stellar_tx only attached when Horizon's tx hash
    matches the tx_id from the same row read
- payment-details cache re-checks the generation before storing and skips
  bodies superseded by a concurrent write (stale_skip)
- no response written after the client disconnected
- metrics: coalesced total, single-flight in-flight, enrichment outcomes
- tests for coalescing, isolation, bulkhead, deadline, mismatch; docs and
  .env.example
@vercel

vercel Bot commented Nov 23, 2026

Copy link
Copy Markdown

@Abidoyesimze is attempting to deploy a commit to the Emmanuel's projects Team on Vercel.

A member of the Team first needs to authorize it.

@drips-wave

drips-wave Bot commented Nov 23, 2026

Copy link
Copy Markdown

@Abidoyesimze Great news! 🎉 Based on an automated assessment of this PR, the linked Wave issue(s) no longer count against your application limits.

You can now already apply to more issues while waiting for a review of this PR. Keep up the great work! 🚀

Learn more about application limits

@emdevelopa
emdevelopa merged commit a84c71f into emdevelopa:main Nov 23, 2026
1 of 4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment