Skip to content

feat(backend): resolve issues #1426 #1427 #1428 — fraud detection & w… - #1593

Merged
emdevelopa merged 1 commit into
emdevelopa:mainfrom
ke747:feature/be-issues-1426-1427-1428-fraud-detection-webhook-improvements
Sep 30, 2026
Merged

emdevelopa merged 1 commit into
emdevelopa:mainfrom
ke747:feature/be-issues-1426-1427-1428-fraud-detection-webhook-improvements

Conversation

@ke747

@ke747 ke747 commented Sep 27, 2026

Copy link
Copy Markdown

…ebhook improvements

Closes #1426
Closes #1427
Closes #1428

#1428 — Add Prometheus alert metrics and health telemetry to Fraud Detection Engine

  • Added 6 new Prometheus metrics to metrics.js:
    • fraudDetectionAlertsFired (Counter) — tracks high-risk alert events by merchant/risk level
    • fraudDetectionHealthStatus (Gauge) — engine & cache health (1=healthy, 0=degraded)
    • fraudDetectionRuleHits (Counter) — per-rule trigger counts (large_amount, stale_payment, etc.)
    • fraudDetectionEngineLatency (Histogram) — per-evaluation latency with p99 tracking
    • fraudDetectionCacheHealth (Gauge) — cache size and capacity telemetry
    • fraudDetectionAnomalyScore (Histogram) — risk score distribution per merchant
  • Instrumented analyzePayment() with latency timers, rule hit counters, alert firing, and anomaly score observation
  • Added getFraudDetectionHealthStatus() export for health endpoint integration
  • Added Prometheus alert rules file: backend/docs/alerts/fraud-detection-engine.rules.yml
    • FraudDetectionEngineHighAlertRate (critical, >10 alerts/sec for 2m)
    • FraudDetectionEngineDegraded (critical, engine health == 0 for 1m)
    • FraudDetectionCacheNearCapacity (warning, >90% full for 5m)
    • FraudDetectionHighLatency (warning, p99 > 100ms for 5m)
    • FraudDetectionSuspiciousAnomalySpike (warning, rule hits > 50/sec for 3m)
    • FraudDetectionErrorRate (critical, errors > 1/sec for 2m)

#1427 — Implement payload sanitization and strict validation for Fraud Detection Engine

  • New file: backend/src/lib/fraud-detection-sanitizer.js
    • Zod-based strict schema validation (fraudDetectionPayloadSchema)
    • Stellar address format validation (/^G[A-Z2-7]{55}$/)
    • Payment status whitelist (pending/completed/failed/expired/refunded)
    • Amount validation (positive numeric string, up to 7 decimal places)
    • Memo sanitization (max 200 chars, control char stripping)
    • Prototype pollution prevention (strips proto, constructor, prototype keys)
    • Metadata sanitization via existing sanitize-metadata utility
    • String truncation guard (max 1000 chars per value)
    • Merchant ID validation (/^[a-zA-Z0-9_-:.@]+$/, max 128 chars)
  • Integrated sanitizeAndValidateFraudPayload() at the entry point of analyzePayment()
  • Integrated validateMerchantId() guard in clearCache()
  • Returns structured validation errors with field paths for observability
  • New test file: backend/src/lib/fraud-detection-sanitizer.test.js
    • 20+ test cases covering valid payloads, XSS, prototype pollution, edge cases

#1426 — Add comprehensive integration and stress test suite for Webhook Event Dispatcher

  • New file: backend/tests/integration/webhook-event-dispatcher.integration.test.js
  • Integration tests (WebhookEventCache):
    • Payload store/retrieve, TTL expiry, LRU eviction
    • Delivery deduplication (first=false, repeat=true, overflow guard)
    • Subscription cache CRUD and invalidation
    • Circuit breaker open/close/reset/per-merchant isolation
    • Cache stats shape validation, clearAll atomicity
    • Payload integrity (nested objects, unicode, large payloads)
    • Special character IDs, overwrite behavior
  • Stress tests:
    • 5000 sequential writes < 500ms
    • 5000 sequential reads < 100ms
    • 1000 concurrent deduplication checks (Promise.all)
    • Cache size enforcement under overflow pressure
    • 50 merchants × 100 subscriptions cached
    • Circuit breaker operations for 100 merchants < 200ms
    • 10000 cache lookups < 200ms throughput SLO
    • Mixed read/write/delete stability under 2000 ops

Housekeeping

  • Updated .gitignore to exclude test-results/, snapshots/, *.snap, playwright-report/, tsconfig.tsbuildinfo, output.txt, logs/, coverage/, .env.local, temp files, IDE artifacts

…opa#1428 — fraud detection & webhook improvements

Closes emdevelopa#1426
Closes emdevelopa#1427
Closes emdevelopa#1428

## emdevelopa#1428 — Add Prometheus alert metrics and health telemetry to Fraud Detection Engine

- Added 6 new Prometheus metrics to metrics.js:
  * fraudDetectionAlertsFired (Counter) — tracks high-risk alert events by merchant/risk level
  * fraudDetectionHealthStatus (Gauge) — engine & cache health (1=healthy, 0=degraded)
  * fraudDetectionRuleHits (Counter) — per-rule trigger counts (large_amount, stale_payment, etc.)
  * fraudDetectionEngineLatency (Histogram) — per-evaluation latency with p99 tracking
  * fraudDetectionCacheHealth (Gauge) — cache size and capacity telemetry
  * fraudDetectionAnomalyScore (Histogram) — risk score distribution per merchant
- Instrumented analyzePayment() with latency timers, rule hit counters, alert firing, and anomaly score observation
- Added getFraudDetectionHealthStatus() export for health endpoint integration
- Added Prometheus alert rules file: backend/docs/alerts/fraud-detection-engine.rules.yml
  * FraudDetectionEngineHighAlertRate (critical, >10 alerts/sec for 2m)
  * FraudDetectionEngineDegraded (critical, engine health == 0 for 1m)
  * FraudDetectionCacheNearCapacity (warning, >90% full for 5m)
  * FraudDetectionHighLatency (warning, p99 > 100ms for 5m)
  * FraudDetectionSuspiciousAnomalySpike (warning, rule hits > 50/sec for 3m)
  * FraudDetectionErrorRate (critical, errors > 1/sec for 2m)

## emdevelopa#1427 — Implement payload sanitization and strict validation for Fraud Detection Engine

- New file: backend/src/lib/fraud-detection-sanitizer.js
  * Zod-based strict schema validation (fraudDetectionPayloadSchema)
  * Stellar address format validation (/^G[A-Z2-7]{55}$/)
  * Payment status whitelist (pending/completed/failed/expired/refunded)
  * Amount validation (positive numeric string, up to 7 decimal places)
  * Memo sanitization (max 200 chars, control char stripping)
  * Prototype pollution prevention (strips __proto__, constructor, prototype keys)
  * Metadata sanitization via existing sanitize-metadata utility
  * String truncation guard (max 1000 chars per value)
  * Merchant ID validation (/^[a-zA-Z0-9_\-:.@]+$/, max 128 chars)
- Integrated sanitizeAndValidateFraudPayload() at the entry point of analyzePayment()
- Integrated validateMerchantId() guard in clearCache()
- Returns structured validation errors with field paths for observability
- New test file: backend/src/lib/fraud-detection-sanitizer.test.js
  * 20+ test cases covering valid payloads, XSS, prototype pollution, edge cases

## emdevelopa#1426 — Add comprehensive integration and stress test suite for Webhook Event Dispatcher

- New file: backend/tests/integration/webhook-event-dispatcher.integration.test.js
- Integration tests (WebhookEventCache):
  * Payload store/retrieve, TTL expiry, LRU eviction
  * Delivery deduplication (first=false, repeat=true, overflow guard)
  * Subscription cache CRUD and invalidation
  * Circuit breaker open/close/reset/per-merchant isolation
  * Cache stats shape validation, clearAll atomicity
  * Payload integrity (nested objects, unicode, large payloads)
  * Special character IDs, overwrite behavior
- Stress tests:
  * 5000 sequential writes < 500ms
  * 5000 sequential reads < 100ms
  * 1000 concurrent deduplication checks (Promise.all)
  * Cache size enforcement under overflow pressure
  * 50 merchants × 100 subscriptions cached
  * Circuit breaker operations for 100 merchants < 200ms
  * 10000 cache lookups < 200ms throughput SLO
  * Mixed read/write/delete stability under 2000 ops

## Housekeeping

- Updated .gitignore to exclude test-results/, __snapshots__/, *.snap, playwright-report/,
  tsconfig.tsbuildinfo, output.txt, logs/, coverage/, .env.local, temp files, IDE artifacts
@drips-wave

drips-wave Bot commented Sep 27, 2026

Copy link
Copy Markdown

@ke747 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

@vercel

vercel Bot commented Sep 27, 2026

Copy link
Copy Markdown

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

A member of the Team first needs to authorize it.

@emdevelopa
emdevelopa merged commit 477bd3c into emdevelopa:main Sep 30, 2026
1 of 2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants