Repository navigation
feat(backend): merchant onboarding validation + caching, hosted checkout caching + concurrency control (#1769, #1770, #1775, #1777) - #1915
Merged
emdevelopa merged 5 commits intoNov 23, 2026
Conversation
- 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
|
@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. |
|
@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! 🚀 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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
main8e375e0. Two breakages onmainmeantsrc/lib/stellar.js, and every route that imports it (includingmerchants.js), failed to load under vitest:horizon-client/sanitizer.js: theCONTROL_CHARS_PATTERNregex contained literal U+2028/U+2029 characters, which are line terminators in JS source, so the regex literal could not be parsed. Replaced them withescapes.horizon-client/retry-manager.js: a merge droppedHealthStatus,HEALTH_STATE_VALUE,MAX_TRACKED_OPERATIONS,resolveUnhealthyThresholdand three metric imports, so constructing the client threwReferenceError. Restored them from 885b3b1.#1769: Input validation and payload sanitization (merchants.js)
validateMerchantRequest()keeps the existing400 { error: "Validation failed", errors }contract. It addsmerchant_payload_rejections_total{route,reason}and logs field names only, never values.register-merchant:api_key,webhook_secret,password_hash, …) return 400.A@x.comanda@x.comcould both register because the lock key lower-cased the email but the existence check did not.business_nameis length-bounded and HTML-safe.rotate-key,regenerate-webhook-secret,generate-api-key,webhook-settings/verify) take no input and now reject any body.merchant-branding/preview-receiptuse a strict schema.logo_urlmust behttps:or a base64 PNG/JPEG/GIF/WebP data URI.test-webhookis now sanitized, HTTPS-only and rejects embedded credentials. The receiver's echoed response body is truncated and stripped of control characters.webhook-settingsuses the same URL rules astest-webhook.renderReceiptEmailinterpolatedlogo_urlandbusiness_namewithout escaping, and/preview-receiptserves that HTML astext/html, so a craftedlogo_urlwas 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.resolveBrandingConfig,sendWebhook,getPayloadForVersion) that madeGET /merchant-brandingandPOST /test-webhookthrowReferenceError.#1770: Redis caching and throughput telemetry (merchants.js)
merchant-profile,merchant-brandingandwebhook-settings. Only the masked webhook response is cached; raw secrets and API keys never reach Redis.api-key-statusis not cached.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.REDIS_CACHE_OP_TIMEOUT_MS). If Redis errors or is down, the request reads the database.route-throughput-telemetry.jsadds 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.Cache-Control: private, no-storeandX-Cache.#1775: Redis caching and throughput telemetry (paymentDetails.js)
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.paymentDetails.js.#1777: Concurrency control and atomic handling (paymentDetails.js)
X-Cache: COALESCED), and a failure is never replayed to later requests.ConcurrencyLimiter) with a response deadline. When it is saturated or slow, the payment is returned withstellar_tx: nullinstead of a 503.stellar_txis attached only when Horizon's hash matches thetx_idfrom the same row read. The cache store is skipped if a writer invalidated during the load.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/:Before the base fix,
merchants.test.js(7 tests),merchant-settings-validation.test.jsand every suite importingsrc/lib/stellar.jsfailed at import time onmain.On
mainthe 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 againstmainwill follow in a comment.Security notes
stellar_tx" behaviour, never to an error response.