A self-hosted UPI & COD payment gateway with zero per-transaction platform fees, universal JavaScript checkout integration, dynamic QR payments, WhatsApp OTP authentication, and automated payment verification.
JavaScript
fix(security): persist terminal webhook events and recover interrupted deliveries
SHIVANSHU SATYAJEET3a8b421763c6
diff --git a/.env.example b/.env.exampleindex f3edcc3..1519b1c 100644--- a/.env.example+++ b/.env.example@@ -65,7 +65,9 @@ ANDROID_ENROLLMENT_SECRET=android_pairing_enrollment_secret_key_32_charsANDROID_HEARTBEAT_TIMEOUT_MS=180000# --- WEBHOOK ENGINE ---+# Minimum 2 attempts; keep receiver idempotent using X-Gateway-Delivery-Id.WEBHOOK_MAX_RETRIES=5+WEBHOOK_RETRY_INTERVAL_MS=5000WEBHOOK_INITIAL_BACKOFF_MS=5000# --- CHECKOUT PORTAL FRAMING ---diff --git a/ARCHITECTURE.md b/ARCHITECTURE.mdindex 32bb7ad..8e4e460 100644--- a/ARCHITECTURE.md+++ b/ARCHITECTURE.md@@ -3,7 +3,7 @@> **YOUPI PG V2**> *Sovereign • Self-Hosted • Zero-Fee • Deterministic UPI Payment Gateway Suite*> **Architecture Reference:** Production Specification V2-> **Runtime Target:** Node.js `>= 20.0.0` (ESM Native) • SQLite WAL • Android Kotlin+> **Runtime Target:** Node.js `>= 24.0.0` (ESM Native) • SQLite WAL • Android Kotlin---diff --git a/README.md b/README.mdindex 1f675f2..dd675d1 100644--- a/README.md+++ b/README.md@@ -65,6 +65,25 @@<br/>+## Security maintenance notes (fork hardening branch)++This repository is **experimental and not independently certified or safe for unattended real-money processing**. Any SUCCESS reported by SMS, push notification or email parsing requires independent bank-ledger reconciliation before fulfillment. WhatsApp OTP is contact verification, not proof of payment or fraud immunity.++### Terminal-webhook crash recovery++A newly terminal payment creates a SQLite **payment_webhook_outbox** entry through a database trigger in the same transaction as the status change. The Payment API prepares a durable `webhook_deliveries` row **before** issuing HTTP requests, then updates delivery status after the HTTP response. Startup recovery and the periodic retry worker replay pending outbox entries and existing delivery rows. Existing historic terminal transactions are **not** automatically re-emitted during migration. A merchant endpoint must deduplicate by `X-Gateway-Delivery-Id` because a crash after receipt can still cause a retry (at-least-once, not exactly-once).++This mitigation does **not** resolve alert spoofing, UPI settlement validation, late and misattributed credits, legal/regulatory obligations, refund disputes or full production readiness.++### Before any deployment++- Run `npm test` and review the CI results; perform controlled crash/restart and observation-replay testing using synthetic data.+- Use distinct randomly generated admin, observer, JWT, encryption and webhook secrets; rotate any keys inherited from prior deployments. Never publish `.env`, bank messages, OTPs, or customer data.+- Review the bank/account terms and applicable UPI/payment-system requirements; do not infer compliance from this code.+- Confirm merchant webhook URLs use HTTPS, verify HMAC over raw request bytes, enforce event/amount/order checks, deduplicate deliveries, and reconcile against official bank records before delivering goods.+- Back up SQLite (including WAL state), monitor outbox backlog and permanently failed webhooks, and provide a human reconciliation/appeal path.+- `npm run dev` is local experimentation; `npm start` requires valid production configuration and must not be exposed casually.+## Live Product DemosSee **YOUPI PG V2** live in action across Desktop and Mobile checkout flows:@@ -234,8 +253,7 @@ This section is a practical project warning, not a certification, compliance che## Quickstart in 60 Seconds### Prerequisites-- **Node.js `>= 22.13.0` LTS** (Recommended: Node 24 LTS, `node -v`) for native `node:sqlite` (`DatabaseSync`) engine.- `node:sqlite` was added in Node 22.5.0 but only unflagged in **22.13.0**, so 22.5.0–22.12.x cannot run this project without `--experimental-sqlite`.+- **Node.js `>= 24.0.0`** (check with `node -v`), as required by `package.json`, for native `node:sqlite`.- Standard Linux, macOS, or Windows host- *External database services (PostgreSQL/Redis) are completely optional!*diff --git a/apps/payment-api/src/index.js b/apps/payment-api/src/index.jsindex 62a4551..f49e42e 100644--- a/apps/payment-api/src/index.js+++ b/apps/payment-api/src/index.js@@ -128,6 +128,7 @@ export function createPaymentApp(customDb = null, options = {}) {const webhookEngine = new WebhookEngine({db,merchantRepo,+ sessionRepo,maxRetries: Number(process.env.WEBHOOK_MAX_RETRIES || 5)});@@ -309,7 +310,7 @@ export function createPaymentApp(customDb = null, options = {}) {// an unhandled error that can take the process down.const webhookRetryDaemon = setInterval(() => {try {- const outcome = webhookEngine.retryPending();+ const outcome = webhookEngine.recoverOutbox().then(() => webhookEngine.retryPending());if (outcome && typeof outcome.catch === 'function') outcome.catch(() => {});} catch {}}, Number(process.env.WEBHOOK_RETRY_INTERVAL_MS || 5000));@@ -332,6 +333,10 @@ export function createPaymentApp(customDb = null, options = {}) {// Execute crash recovery on bootconst recoveryStats = recoveryEngine.recover();+ // Replay only outboxed transitions that lack a durable delivery record.+ webhookEngine.recoverOutbox().catch(err => {+ console.error('[webhook] Failed to recover terminal-event outbox:', err.message);+ });// Health check routesconst healthHandler = (req, res) => {diff --git a/packages/core/src/__tests__/webhook-outbox-durability.test.js b/packages/core/src/__tests__/webhook-outbox-durability.test.jsnew file mode 100644index 0000000..8b4a3eb--- /dev/null+++ b/packages/core/src/__tests__/webhook-outbox-durability.test.js@@ -0,0 +1,97 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import '../../../../scripts/test-support.js';+import { Database, runMigrations, MerchantRepository, PaymentSessionRepository } from '@youpi/db';+import { WebhookEngine } from '../webhook-engine.js';++function fixture(slug) {+ const db = new Database({ inMemory: true });+ runMigrations(db);+ const merchants = new MerchantRepository(db);+ const sessions = new PaymentSessionRepository(db);+ const merchant = merchants.create({+ businessName: 'Synthetic webhook fixture',+ slug,+ contactEmail: slug + '@example.com',+ contactPhone: '9000000000',+ webhookUrl: 'http://localhost:54321/webhook',+ webhookSecret: 'synthetic_hmac_secret_for_webhook_tests'+ });+ const engine = new WebhookEngine({ db, merchantRepo: merchants, sessionRepo: sessions });+ return { db, merchants, sessions, merchant, engine };+}++test('outbox survives terminal transition and is prepared before network dispatch', async () => {+ const { db, sessions, merchant, engine } = fixture('durable-terminal');+ const previousFetch = globalThis.fetch;+ try {+ const session = sessions.create({ merchantId: merchant.id, orderId: 'DURABLE-1', amountPaise: 100n, status: 'ACTIVE' });+ sessions.transitionToTerminal(session.id, 'EXPIRED');+ assert.equal(db.queryOne('SELECT event_type FROM payment_webhook_outbox WHERE payment_id = ?', [session.id]).event_type, 'EXPIRED');++ let requestCount = 0;+ globalThis.fetch = async (_url, opts) => {+ requestCount++;+ const row = db.queryOne('SELECT * FROM webhook_deliveries WHERE payment_id = ?', [session.id]);+ assert.ok(row, 'delivery MUST be durable before fetch');+ assert.equal(row.is_successful, 0);+ assert.equal(row.attempt_count, 1);+ assert.ok(row.next_retry_at, 'crash recovery lease MUST be set');+ assert.equal(row.id, opts.headers['X-Gateway-Delivery-Id']);+ return { ok: true, status: 200, text: async () => 'ok' };+ };++ const recovered = await engine.recoverOutbox();+ assert.equal(recovered.length, 1);+ assert.equal(recovered[0].delivered, true);+ assert.equal(requestCount, 1);+ assert.equal(db.queryOne('SELECT COUNT(*) AS n FROM payment_webhook_outbox WHERE payment_id = ?', [session.id]).n, 0);+ assert.equal((await engine.recoverOutbox()).length, 0);+ const duplicate = await engine.dispatch('EXPIRED', sessions.findById(session.id));+ assert.equal(duplicate.deliveryId, recovered[0].deliveryId);+ assert.equal(requestCount, 1, 'duplicate terminal events MUST NOT issue another delivery');+ } finally {+ globalThis.fetch = previousFetch;+ db.close();+ }+});++test('interrupted first attempt remains eligible for restart retry with the same delivery ID and body', async () => {+ const { db, sessions, merchant, engine, merchants } = fixture('durable-restart');+ const previousFetch = globalThis.fetch;+ try {+ const session = sessions.create({ merchantId: merchant.id, orderId: 'DURABLE-2', amountPaise: 200n });+ let initialBody;+ globalThis.fetch = async (_url, opts) => {+ const row = db.queryOne('SELECT * FROM webhook_deliveries WHERE payment_id = ?', [session.id]);+ assert.ok(row, 'network must not start before persistence');+ initialBody = opts.body;+ assert.equal(row.payload, initialBody);+ throw new Error('synthetic network failure');+ };+ const failed = await engine.dispatch('SUCCESS', session);+ assert.equal(failed.delivered, false);+ const pending = db.queryOne('SELECT * FROM webhook_deliveries WHERE id = ?', [failed.deliveryId]);+ assert.equal(pending.is_successful, 0);+ assert.equal(pending.attempt_count, 1);+ assert.ok(pending.next_retry_at);++ db.execute('UPDATE webhook_deliveries SET next_retry_at = ? WHERE id = ?', [new Date(Date.now() - 1000).toISOString(), pending.id]);+ const afterRestart = new WebhookEngine({ db, merchantRepo: merchants, sessionRepo: sessions });+ let resent = 0;+ globalThis.fetch = async (_url, opts) => {+ resent++;+ assert.equal(opts.headers['X-Gateway-Delivery-Id'], pending.id);+ assert.equal(opts.body, initialBody);+ return { ok: true, status: 200, text: async () => 'ok' };+ };+ const results = await afterRestart.retryPending();+ assert.equal(results.length, 1);+ assert.equal(results[0].success, true);+ assert.equal(resent, 1);+ assert.equal(db.queryOne('SELECT is_successful FROM webhook_deliveries WHERE id = ?', [pending.id]).is_successful, 1);+ } finally {+ globalThis.fetch = previousFetch;+ db.close();+ }+});diff --git a/packages/core/src/webhook-engine.js b/packages/core/src/webhook-engine.jsindex 8ca9fc8..b2ad185 100644--- a/packages/core/src/webhook-engine.js+++ b/packages/core/src/webhook-engine.js@@ -1,4 +1,5 @@import crypto from 'node:crypto';+import { PaymentSessionRepository } from '@youpi/db';import { generateHmac, toRupeesString, validateOutboundWebhookUrl } from '@youpi/common';import { isTerminalStatus, toPublicOutcome } from './state-machine.js';@@ -13,7 +14,8 @@ export class WebhookEngine {constructor(options) {this.db = options.db;this.merchantRepo = options.merchantRepo;- this.maxRetries = options.maxRetries || 5;+ this.sessionRepo = options.sessionRepo || new PaymentSessionRepository(this.db);+ this.maxRetries = Math.max(2, Math.min(20, Number(options.maxRetries) || 5));}/**@@ -31,6 +33,16 @@ export class WebhookEngine {const publicOutcome = isTerminalStatus(event) ? toPublicOutcome(event) : event;const nowIso = new Date().toISOString();+ // One durable delivery per payment/event, including duplicate or replayed in-process+ // events. SQLite serializes the final create-or-read in the transaction below.+ const prior = this.db.queryOne(+ 'SELECT id, is_successful, response_status, response_body FROM webhook_deliveries WHERE payment_id = ? AND event_type = ? ORDER BY created_at DESC LIMIT 1',+ [session.id, publicOutcome]+ );+ if (prior) {+ return { delivered: Boolean(prior.is_successful), deliveryId: prior.id, status: prior.response_status, error: prior.is_successful ? undefined : prior.response_body };+ }+// 1. Up-front secret validation: if webhookSecret is missing, persist a failed row so it is auditableif (!merchant.webhookSecret) {const deliveryId = crypto.randomUUID();@@ -123,6 +135,30 @@ export class WebhookEngine {'X-Gateway-Timestamp': timestamp};+ // Persist BEFORE network IO. A worker dying during fetch must leave an eligible+ // retry with its original deliveryId, timestamp and exact payload bytes.+ // The 60s lease avoids two senders racing while an attempt is in flight.+ const recoveryAt = new Date(Date.now() + 60000).toISOString();+ const existing = this.db.transaction(() => {+ const row = this.db.queryOne(+ 'SELECT id, is_successful, response_status, response_body FROM webhook_deliveries WHERE payment_id = ? AND event_type = ? ORDER BY created_at DESC LIMIT 1',+ [session.id, publicOutcome]+ );+ if (row) return row;+ this.db.execute(`+ INSERT INTO webhook_deliveries (+ id, merchant_id, payment_id, event_type, payload, endpoint_url,+ response_status, response_body, attempt_count, is_successful, next_retry_at, created_at+ ) VALUES (?, ?, ?, ?, ?, ?, NULL, NULL, 1, 0, ?, ?)+ `, [deliveryId, merchant.id, session.id, publicOutcome, payloadString, merchant.webhookUrl, recoveryAt, nowIso]);+ // Outbox cleanup commits together with durable delivery preparation.+ this.db.execute('DELETE FROM payment_webhook_outbox WHERE payment_id = ?', [session.id]);+ return null;+ });+ if (existing) {+ return { delivered: Boolean(existing.is_successful), deliveryId: existing.id, status: existing.response_status, error: existing.is_successful ? undefined : existing.response_body };+ }+let responseStatus = null;let responseBody = null;let isSuccessful = false;@@ -144,29 +180,15 @@ export class WebhookEngine {responseBody = err.message || 'Network timeout';}- // Persist delivery record in webhook_deliveriesconst nextRetryAt = isSuccessful? null- : new Date(Date.now() + 5000).toISOString(); // initial 5s backoff+ : new Date(Date.now() + 5000).toISOString();this.db.execute(`- INSERT INTO webhook_deliveries (- id, merchant_id, payment_id, event_type, payload, endpoint_url,- response_status, response_body, attempt_count, is_successful, next_retry_at, created_at- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?)- `, [- deliveryId,- merchant.id,- session.id,- publicOutcome,- payloadString,- merchant.webhookUrl,- responseStatus,- responseBody,- isSuccessful ? 1 : 0,- nextRetryAt,- nowIso- ]);+ UPDATE webhook_deliveries+ SET response_status = ?, response_body = ?, is_successful = ?, next_retry_at = ?+ WHERE id = ?+ `, [responseStatus, responseBody, isSuccessful ? 1 : 0, nextRetryAt, deliveryId]);return {delivered: isSuccessful,@@ -176,6 +198,33 @@ export class WebhookEngine {};}+ /**+ * Prepare and send terminal events committed before a crash but not yet turned+ * into delivery records. The trigger records only new terminal transitions;+ * historic SUCCESS rows are never swept into webhooks on upgrade.+ */+ async recoverOutbox() {+ const rows = this.db.query(`+ SELECT o.payment_id, o.event_type+ FROM payment_webhook_outbox o+ WHERE NOT EXISTS (+ SELECT 1 FROM webhook_deliveries d+ WHERE d.payment_id = o.payment_id AND d.event_type = o.event_type+ )+ ORDER BY o.created_at, o.payment_id LIMIT 20+ `);+ const outcomes = [];+ for (const row of rows) {+ const session = this.sessionRepo.findById(row.payment_id);+ if (!session) continue;+ const merchant = this.merchantRepo.findById(session.merchantId);+ // Keep unconfigured merchants' events in the outbox for human remediation.+ if (!merchant?.webhookUrl || !merchant.webhookSecret) continue;+ outcomes.push(await this.dispatch(row.event_type, session));+ }+ return outcomes;+ }+/*** Retries overdue pending webhook deliveries with atomic claim & exponential backoff.* Backoff strategy: 5s, 30s, 2m, 10m, 1hdiff --git a/packages/db/src/schema.sql b/packages/db/src/schema.sqlindex 344fb6c..8ec9d95 100644--- a/packages/db/src/schema.sql+++ b/packages/db/src/schema.sql@@ -195,6 +195,23 @@ CREATE TABLE IF NOT EXISTS webhook_deliveries (CREATE INDEX IF NOT EXISTS idx_webhook_deliveries_retry ON webhook_deliveries (is_successful, next_retry_at);+-- Durable terminal-event outbox: populated in the same SQLite transaction as the status update.+-- Only NEW terminal transitions are queued; migrations must never replay historic orders.+CREATE TABLE IF NOT EXISTS payment_webhook_outbox (+ payment_id TEXT PRIMARY KEY REFERENCES payment_sessions(id) ON DELETE CASCADE,+ event_type TEXT NOT NULL CHECK(event_type IN ('SUCCESS','FAILED','EXPIRED','CANCELLED')),+ created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))+);++CREATE TRIGGER IF NOT EXISTS trg_terminal_payment_webhook_outbox+AFTER UPDATE OF status ON payment_sessions+WHEN NEW.status IN ('SUCCESS','FAILED','EXPIRED','CANCELLED')+ AND OLD.status NOT IN ('SUCCESS','FAILED','EXPIRED','CANCELLED')+BEGIN+ INSERT OR IGNORE INTO payment_webhook_outbox (payment_id, event_type)+ VALUES (NEW.id, NEW.status);+END;+-- 8. Support Tickets & Ticket MessagesCREATE TABLE IF NOT EXISTS support_tickets (id TEXT PRIMARY KEY,diff --git a/packages/db/src/sqlite-schema.sql b/packages/db/src/sqlite-schema.sqlindex 0a02841..d0218a2 100644--- a/packages/db/src/sqlite-schema.sql+++ b/packages/db/src/sqlite-schema.sql@@ -198,6 +198,23 @@ CREATE TABLE IF NOT EXISTS webhook_deliveries (CREATE INDEX IF NOT EXISTS idx_webhook_deliveries_retry ON webhook_deliveries (is_successful, next_retry_at);+-- Durable terminal-event outbox: populated in the same SQLite transaction as the status update.+-- Only NEW terminal transitions are queued; migrations must never replay historic orders.+CREATE TABLE IF NOT EXISTS payment_webhook_outbox (+ payment_id TEXT PRIMARY KEY REFERENCES payment_sessions(id) ON DELETE CASCADE,+ event_type TEXT NOT NULL CHECK(event_type IN ('SUCCESS','FAILED','EXPIRED','CANCELLED')),+ created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))+);++CREATE TRIGGER IF NOT EXISTS trg_terminal_payment_webhook_outbox+AFTER UPDATE OF status ON payment_sessions+WHEN NEW.status IN ('SUCCESS','FAILED','EXPIRED','CANCELLED')+ AND OLD.status NOT IN ('SUCCESS','FAILED','EXPIRED','CANCELLED')+BEGIN+ INSERT OR IGNORE INTO payment_webhook_outbox (payment_id, event_type)+ VALUES (NEW.id, NEW.status);+END;+-- 8. Support Tickets & Ticket MessagesCREATE TABLE IF NOT EXISTS support_tickets (id TEXT PRIMARY KEY,