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(webhooks): persist write-ahead delivery row and recover interrupted webhooks on crash (Closes #86)
Harsh5b5e3a733020
diff --git a/apps/payment-api/src/index.js b/apps/payment-api/src/index.jsindex 62a4551..156c2df 100644--- a/apps/payment-api/src/index.js+++ b/apps/payment-api/src/index.js@@ -115,22 +115,23 @@ export function createPaymentApp(customDb = null, options = {}) {eventEmitter});+ const webhookEngine = new WebhookEngine({+ db,+ merchantRepo,+ maxRetries: Number(process.env.WEBHOOK_MAX_RETRIES || 5)+ });+const recoveryEngine = new RecoveryEngine({db,sessionRepo,accountRepo,queueEngine,timingEngine,+ webhookEngine,auditRepo,eventEmitter});- const webhookEngine = new WebhookEngine({- db,- merchantRepo,- maxRetries: Number(process.env.WEBHOOK_MAX_RETRIES || 5)- });-const server = new HttpServer();server.use(authGuard);let checkoutBaseUrl = process.env.BASE_CHECKOUT_URL || 'http://localhost:7000';@@ -330,8 +331,13 @@ export function createPaymentApp(customDb = null, options = {}) {gmailPort: Number(process.env.GMAIL_OBSERVER_PORT || 6003)});- // Execute crash recovery on boot+ // Execute crash recovery on boot (AFTER event listeners are wired so recovered terminal transitions emit webhooks)const recoveryStats = recoveryEngine.recover();+ // Immediately kick off a background retry sweep for any recovered in-flight or backfilled webhooks+ try {+ const initialRetry = webhookEngine.retryPending();+ if (initialRetry && typeof initialRetry.catch === 'function') initialRetry.catch(() => {});+ } catch {}// Health check routesconst healthHandler = (req, res) => {diff --git a/packages/core/src/__tests__/webhook-engine.test.js b/packages/core/src/__tests__/webhook-engine.test.jsindex 7b96272..bbdc673 100644--- a/packages/core/src/__tests__/webhook-engine.test.js+++ b/packages/core/src/__tests__/webhook-engine.test.js@@ -1,6 +1,10 @@import { test, describe, before, after } from 'node:test';import assert from 'node:assert/strict';import http from 'node:http';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { spawn } from 'node:child_process';import '../../../../scripts/test-support.js';import { Database, runMigrations, MerchantRepository, PaymentSessionRepository, ObservationRepository } from '@youpi/db';import { WebhookEngine } from '../webhook-engine.js';@@ -284,4 +288,167 @@ describe('Webhook Engine Integration Tests', () => {assert.equal(recorded.response_status, 500);assert.match(recorded.response_body, /webhookSecret is not configured/);});++ test('survives SIGKILL mid-first-delivery and delivers webhook on restart (Issue #86)', async () => {+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'youpi-wh-crash-'));+ const dbPath = path.join(tmpDir, 'crash-test.db');++ let acceptRequests = false;+ let firstAttemptSeenResolve;+ const firstAttemptSeen = new Promise(resolve => { firstAttemptSeenResolve = resolve; });+ const deliveredPayloads = [];++ const hangServer = http.createServer((req, res) => {+ let body = '';+ req.on('data', chunk => { body += chunk; });+ req.on('end', () => {+ if (!acceptRequests) {+ // Signal that the first delivery request reached the server, then hang so child can be SIGKILLed+ firstAttemptSeenResolve();+ return;+ }+ deliveredPayloads.push({+ headers: req.headers,+ body: JSON.parse(body || '{}')+ });+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ received: true }));+ });+ });++ const hangPort = await new Promise(resolve => {+ hangServer.listen(0, '127.0.0.1', () => resolve(hangServer.address().port));+ });++ try {+ // Spawn a child process that creates a terminal payment session and calls dispatch(),+ // which will hang waiting for hangServer while we SIGKILL the child process.+ const childScript = `+ import './scripts/test-support.js';+ import { Database, runMigrations, MerchantRepository, PaymentSessionRepository } from '@youpi/db';+ import { WebhookEngine } from '@youpi/core';++ const db = new Database({ dbPath: process.env.CRASH_DB_PATH });+ runMigrations(db);+ const merchantRepo = new MerchantRepository(db);+ const sessionRepo = new PaymentSessionRepository(db);+ const webhookEngine = new WebhookEngine({ db, merchantRepo, maxRetries: 3 });++ const merchant = merchantRepo.create({+ businessName: 'Crash Test Store',+ slug: 'crash-test-store',+ contactEmail: '[email protected]',+ contactPhone: '9876543210',+ webhookUrl: process.env.CRASH_WEBHOOK_URL,+ webhookSecret: 'crash_secret_key_123456'+ });++ const session = sessionRepo.create({+ merchantId: merchant.id,+ orderId: 'HOOK-ORD-SIGKILL-86',+ amountPaise: 49900n+ });+ sessionRepo.transitionToTerminal(session.id, 'SUCCESS');+ const updatedSession = sessionRepo.findById(session.id);++ await webhookEngine.dispatch('SUCCESS', updatedSession);+ `;++ const child = spawn(process.execPath, ['--input-type=module', '-e', childScript], {+ cwd: path.resolve(import.meta.dirname, '../../../..'),+ env: {+ ...process.env,+ CRASH_DB_PATH: dbPath,+ CRASH_WEBHOOK_URL: `http://localhost:${hangPort}/webhook-crash`+ },+ stdio: 'ignore'+ });++ // Wait until the first HTTP delivery request is in-flight at hangServer+ await firstAttemptSeen;++ // Kill the child process with SIGKILL while the first webhook delivery is in flight+ child.kill('SIGKILL');+ await new Promise(resolve => child.once('exit', resolve));++ // Now open the SQLite DB in the parent (simulating API restart)+ const restartedDb = new Database({ dbPath });+ const restartedMerchantRepo = new MerchantRepository(restartedDb);+ const restartedWebhookEngine = new WebhookEngine({+ db: restartedDb,+ merchantRepo: restartedMerchantRepo,+ maxRetries: 3+ });++ // Verify the write-ahead webhook_deliveries row was persisted before fetch()+ const preRow = restartedDb.queryOne(+ "SELECT * FROM webhook_deliveries WHERE json_extract(payload, '$.orderId') = 'HOOK-ORD-SIGKILL-86'"+ );+ assert.ok(preRow, 'webhook_deliveries row must exist even when process crashed mid-first-delivery');+ assert.equal(preRow.is_successful, 0);+ assert.equal(preRow.attempt_count, 0);++ // Run startup recovery to reset in-flight leases and backfill any missing rows+ const recovered = restartedWebhookEngine.recoverMissingDeliveries({ resetInFlight: true });+ assert.ok(recovered >= 1, 'recoverMissingDeliveries should reset the interrupted in-flight row');++ // Allow receiver to respond 200 OK and run retryPending()+ acceptRequests = true;+ const retryOutcome = await restartedWebhookEngine.retryPending();+ assert.equal(retryOutcome.length, 1);+ assert.equal(retryOutcome[0].success, true);++ assert.equal(deliveredPayloads.length, 1);+ assert.equal(deliveredPayloads[0].body.orderId, 'HOOK-ORD-SIGKILL-86');+ assert.equal(deliveredPayloads[0].body.event, 'SUCCESS');++ const postRow = restartedDb.queryOne('SELECT * FROM webhook_deliveries WHERE id = ?', [preRow.id]);+ assert.equal(postRow.is_successful, 1);+ assert.equal(postRow.response_status, 200);++ restartedDb.close();+ } finally {+ await new Promise(cb => hangServer.close(cb));+ fs.rmSync(tmpDir, { recursive: true, force: true });+ }+ });++ test('backfills and delivers webhook if process crashed between transitionToTerminal and dispatch (Issue #86)', async () => {+ const merchant = merchantRepo.create({+ businessName: 'Orphan Terminal Store',+ slug: 'orphan-terminal-store',+ contactEmail: '[email protected]',+ contactPhone: '9876543210',+ webhookUrl: `http://localhost:${receiverPort}/webhook-orphan`,+ webhookSecret: 'orphan_secret_key_123456'+ });++ const session = sessionRepo.create({+ merchantId: merchant.id,+ orderId: 'HOOK-ORD-ORPHAN-86',+ amountPaise: 35000n+ });+ // Transition session to terminal state WITHOUT calling webhookEngine.dispatch()+ // (simulating crash right after DB commit of terminal state before event listener ran)+ sessionRepo.transitionToTerminal(session.id, 'SUCCESS');++ const beforeRow = db.queryOne('SELECT * FROM webhook_deliveries WHERE payment_id = ?', [session.id]);+ assert.equal(beforeRow, null);++ receivedWebhooks = [];+ shouldReceiverFail = false;++ const retryResults = await webhookEngine.retryPending();+ const matching = retryResults.find(r => {+ const row = db.queryOne('SELECT payment_id FROM webhook_deliveries WHERE id = ?', [r.id]);+ return row && row.payment_id === session.id;+ });+ assert.ok(matching, 'retryPending should backfill and deliver the missing terminal webhook');+ assert.equal(matching.success, true);++ const hook = receivedWebhooks.find(h => h.body.orderId === 'HOOK-ORD-ORPHAN-86');+ assert.ok(hook, 'merchant should receive backfilled webhook');+ assert.equal(hook.body.event, 'SUCCESS');+ assert.equal(hook.body.amountPaise, 35000);+ });});diff --git a/packages/core/src/recovery-engine.js b/packages/core/src/recovery-engine.jsindex 73e0ae1..40bbd8e 100644--- a/packages/core/src/recovery-engine.js+++ b/packages/core/src/recovery-engine.js@@ -8,6 +8,7 @@ export class RecoveryEngine {* accountRepo: import('@youpi/db').ReceivingAccountRepository,* queueEngine: import('./queue-engine.js').QueueEngine,* timingEngine: import('./timing-engine.js').TimingEngine,+ * webhookEngine?: import('./webhook-engine.js').WebhookEngine,* auditRepo?: import('@youpi/db').AuditLogRepository,* eventEmitter?: { emit: (event: string, payload: any) => void }* }} options@@ -18,6 +19,7 @@ export class RecoveryEngine {this.accountRepo = options.accountRepo;this.queueEngine = options.queueEngine;this.timingEngine = options.timingEngine;+ this.webhookEngine = options.webhookEngine;this.auditRepo = options.auditRepo;this.eventEmitter = options.eventEmitter;}@@ -149,11 +151,20 @@ export class RecoveryEngine {}}+ // 6. Recover in-flight or missing terminal webhook deliveries+ let recoveredWebhooksCount = 0;+ if (this.webhookEngine && typeof this.webhookEngine.recoverMissingDeliveries === 'function') {+ try {+ recoveredWebhooksCount = this.webhookEngine.recoverMissingDeliveries({ resetInFlight: true });+ } catch {}+ }+return {expiredCount,failedCount,rescheduledCount,- promotedCount+ promotedCount,+ recoveredWebhooksCount};}}diff --git a/packages/core/src/webhook-engine.js b/packages/core/src/webhook-engine.jsindex 8ca9fc8..ef15690 100644--- a/packages/core/src/webhook-engine.js+++ b/packages/core/src/webhook-engine.js@@ -16,14 +16,71 @@ export class WebhookEngine {this.maxRetries = options.maxRetries || 5;}+ /**+ * Builds the canonical webhook payload object for a payment session and outcome.+ * @param {string} publicOutcome+ * @param {any} session+ * @param {string} deliveryId+ * @param {number} timestampNum+ */+ _buildPayload(publicOutcome, session, deliveryId, timestampNum) {+ // Resolve UTR / bank reference number if attributed.+ // The bank reference (UTR/RRN) lives on the attributed observation, not on the+ // session row. Merchants need it to reconcile a webhook against their bank+ // statement, and it is part of the documented webhook contract.+ let utr = session.utr || session.bankReferenceNumber || session.bank_reference_number || '';+ const attributedObsId = session.attributedObservationId || session.attributed_observation_id;+ if (!utr && attributedObsId) {+ try {+ const obsRow = this.db.queryOne(+ 'SELECT bank_reference_number FROM payment_observations WHERE id = ?',+ [attributedObsId]+ );+ if (obsRow?.bank_reference_number) utr = obsRow.bank_reference_number;+ } catch {}+ }++ const amountPaiseVal = session.amountPaise !== undefined ? session.amountPaise : session.amount_paise;+ const orderIdVal = session.orderId || session.order_id;+ const attemptIdVal = session.attemptId || session.attempt_id || session.id;+ const completedAtRaw = session.completedAt || session.completed_at;+ let metadataVal = session.metadata;+ if (typeof metadataVal === 'string') {+ try { metadataVal = JSON.parse(metadataVal); } catch { metadataVal = {}; }+ }++ return {+ event: publicOutcome,+ deliveryId,+ timestamp: timestampNum,+ paymentId: session.id,+ orderId: orderIdVal,+ attemptId: attemptIdVal,+ amount: toRupeesString(amountPaiseVal),+ amountPaise: Number(amountPaiseVal),+ currency: session.currency || 'INR',+ method: session.method || 'UPI',+ utr: String(utr || ''),+ verificationTag: session.verificationTag || session.verification_tag || (session.method === 'COD' ? 'COD_ORDER_PLACED' : 'UNVERIFIED'),+ verificationLevel: session.verificationLevel != null ? Number(session.verificationLevel) : (session.verification_level != null ? Number(session.verification_level) : (session.method === 'COD' ? 1 : 0)),+ completedAt: completedAtRaw ? (typeof completedAtRaw.toISOString === 'function' ? completedAtRaw.toISOString() : String(completedAtRaw)) : new Date().toISOString(),+ metadata: metadataVal || {}+ };+ }+/*** Formats and dispatches a signed webhook for a payment event.+ * Persists the pending delivery row in `webhook_deliveries` BEFORE making the outbound+ * HTTP call so that if the process crashes while the first delivery is in flight,+ * `retryPending()` will pick up and deliver the webhook upon restart.+ ** @param {string} event E.g. 'SUCCESS', 'FAILED', 'EXPIRED', 'CANCELLED'* @param {any} session The payment session entity* @returns {Promise<{ delivered: boolean, deliveryId: string, status?: number, error?: string }>}*/async dispatch(event, session) {- const merchant = this.merchantRepo.findById(session.merchantId);+ const merchantId = session.merchantId || session.merchant_id;+ const merchant = this.merchantRepo.findById(merchantId);if (!merchant || !merchant.webhookUrl) {return { delivered: false, deliveryId: '', error: 'No webhook URL configured for merchant.' };}@@ -44,7 +101,7 @@ export class WebhookEngine {merchant.id,session.id,publicOutcome,- JSON.stringify({ error: 'Missing webhookSecret', paymentId: session.id, orderId: session.orderId }),+ JSON.stringify({ error: 'Missing webhookSecret', paymentId: session.id, orderId: session.orderId || session.order_id }),merchant.webhookUrl,nowIso]);@@ -65,7 +122,7 @@ export class WebhookEngine {merchant.id,session.id,publicOutcome,- JSON.stringify({ error: 'SSRF blocked', paymentId: session.id, orderId: session.orderId }),+ JSON.stringify({ error: 'SSRF blocked', paymentId: session.id, orderId: session.orderId || session.order_id }),merchant.webhookUrl,`Webhook delivery blocked: ${endpointCheck.error}`,nowIso@@ -73,44 +130,58 @@ export class WebhookEngine {return { delivered: false, deliveryId, status: 400, error: `Webhook delivery blocked: ${endpointCheck.error}` };}- // 3. Resolve UTR / bank reference number if attributed- // The bank reference (UTR/RRN) lives on the attributed observation, not on the- // session row. Merchants need it to reconcile a webhook against their bank- // statement, and it is part of the documented webhook contract.- let utr = session.utr || session.bankReferenceNumber || session.bank_reference_number || '';- if (!utr && session.attributedObservationId) {+ // 3. Persist pending delivery row BEFORE outbound HTTP request (crash-safe write-ahead record).+ // Check if an unsent row already exists for this payment + event (e.g., created by recovery backfill).+ const existingPending = this.db.queryOne(`+ SELECT id, payload FROM webhook_deliveries+ WHERE payment_id = ? AND event_type = ? AND is_successful = 0+ ORDER BY created_at DESC LIMIT 1+ `, [session.id, publicOutcome]);++ let deliveryId;+ let timestamp;+ let payloadString;+ const inFlightLeaseIso = new Date(Date.now() + 15000).toISOString();++ if (existingPending && existingPending.payload) {+ deliveryId = existingPending.id;+ payloadString = existingPending.payload;+ let parsedTs = null;try {- const obsRow = this.db.queryOne(- 'SELECT bank_reference_number FROM payment_observations WHERE id = ?',- [session.attributedObservationId]- );- if (obsRow?.bank_reference_number) utr = obsRow.bank_reference_number;+ const parsed = JSON.parse(payloadString);+ if (parsed && parsed.timestamp != null) parsedTs = String(parsed.timestamp);+ if (parsed && parsed.deliveryId) deliveryId = String(parsed.deliveryId);} catch {}- }-- const deliveryId = crypto.randomUUID();- const timestampNum = Date.now();- const timestamp = timestampNum.toString();+ timestamp = parsedTs || Date.now().toString();+ this.db.execute(`+ UPDATE webhook_deliveries+ SET next_retry_at = ?, endpoint_url = ?+ WHERE id = ?+ `, [inFlightLeaseIso, merchant.webhookUrl, existingPending.id]);+ } else {+ deliveryId = crypto.randomUUID();+ const timestampNum = Date.now();+ timestamp = timestampNum.toString();+ const payloadObj = this._buildPayload(publicOutcome, session, deliveryId, timestampNum);+ payloadString = JSON.stringify(payloadObj);- const payloadObj = {- event: publicOutcome,- deliveryId,- timestamp: timestampNum,- paymentId: session.id,- orderId: session.orderId,- attemptId: session.attemptId || session.id,- amount: toRupeesString(session.amountPaise),- amountPaise: Number(session.amountPaise),- currency: session.currency || 'INR',- method: session.method || 'UPI',- utr: String(utr || ''),- verificationTag: session.verificationTag || session.verification_tag || (session.method === 'COD' ? 'COD_ORDER_PLACED' : 'UNVERIFIED'),- verificationLevel: session.verificationLevel != null ? Number(session.verificationLevel) : (session.verification_level != null ? Number(session.verification_level) : (session.method === 'COD' ? 1 : 0)),- completedAt: session.completedAt ? (typeof session.completedAt.toISOString === 'function' ? session.completedAt.toISOString() : String(session.completedAt)) : new Date().toISOString(),- metadata: session.metadata || {}- };+ 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, 0, 0, ?, ?)+ `, [+ deliveryId,+ merchant.id,+ session.id,+ publicOutcome,+ payloadString,+ merchant.webhookUrl,+ inFlightLeaseIso,+ nowIso+ ]);+ }- const payloadString = JSON.stringify(payloadObj);const signature = generateHmac(payloadString, merchant.webhookSecret);const timestampedSignature = generateHmac(`${timestamp}.${payloadString}`, merchant.webhookSecret);@@ -144,28 +215,25 @@ export class WebhookEngine {responseBody = err.message || 'Network timeout';}- // Persist delivery record in webhook_deliveries+ // 4. Finalize the delivery record in webhook_deliveriesconst nextRetryAt = isSuccessful? null: new Date(Date.now() + 5000).toISOString(); // initial 5s backoffthis.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, ?, ?, ?)+ UPDATE webhook_deliveries+ SET response_status = ?,+ response_body = ?,+ attempt_count = MAX(1, attempt_count + 1),+ is_successful = ?,+ next_retry_at = ?+ WHERE id = ?`, [- deliveryId,- merchant.id,- session.id,- publicOutcome,- payloadString,- merchant.webhookUrl,responseStatus,responseBody,isSuccessful ? 1 : 0,nextRetryAt,- nowIso+ existingPending ? existingPending.id : deliveryId]);return {@@ -176,11 +244,89 @@ export class WebhookEngine {};}+ /**+ * Recovers webhook deliveries that were interrupted mid-flight by a process crash+ * or terminal payment sessions that transitioned just before `dispatch()` could run.+ *+ * @param {{ resetInFlight?: boolean }} [options]+ * @returns {number} Number of recovered/backfilled webhook delivery rows+ */+ recoverMissingDeliveries(options = {}) {+ const { resetInFlight = false } = options;+ const nowIso = new Date().toISOString();+ let recoveredCount = 0;++ if (resetInFlight) {+ // Any row with attempt_count = 0 and response_status IS NULL was in-flight when the previous process died.+ // Reset its next_retry_at to now so retryPending() claims it immediately on boot.+ const res = this.db.execute(`+ UPDATE webhook_deliveries+ SET next_retry_at = ?+ WHERE is_successful = 0 AND attempt_count = 0 AND response_status IS NULL+ `, [nowIso]);+ recoveredCount += Number(res?.changes || 0);+ }++ // Find terminal payment sessions for merchants with configured webhooks that have NO webhook_deliveries row at all.+ const orphanedSessions = this.db.query(`+ SELECT ps.*+ FROM payment_sessions ps+ JOIN merchants m ON m.id = ps.merchant_id+ WHERE ps.status IN ('SUCCESS', 'FAILED', 'EXPIRED', 'CANCELLED')+ AND m.webhook_url IS NOT NULL AND m.webhook_url != ''+ AND m.webhook_secret IS NOT NULL AND m.webhook_secret != ''+ AND NOT EXISTS (+ SELECT 1 FROM webhook_deliveries wd WHERE wd.payment_id = ps.id+ )+ LIMIT 100+ `);++ for (const sessionRow of orphanedSessions) {+ const merchant = this.merchantRepo.findById(sessionRow.merchant_id);+ if (!merchant || !merchant.webhookUrl || !merchant.webhookSecret) continue;++ const endpointCheck = validateOutboundWebhookUrl(merchant.webhookUrl);+ if (!endpointCheck.valid) continue;++ const publicOutcome = isTerminalStatus(sessionRow.status)+ ? toPublicOutcome(sessionRow.status)+ : sessionRow.status;+ const deliveryId = crypto.randomUUID();+ const timestampNum = Date.now();+ const payloadObj = this._buildPayload(publicOutcome, sessionRow, deliveryId, timestampNum);+ const payloadString = JSON.stringify(payloadObj);++ 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, 0, 0, ?, ?)+ `, [+ deliveryId,+ merchant.id,+ sessionRow.id,+ publicOutcome,+ payloadString,+ merchant.webhookUrl,+ nowIso,+ nowIso+ ]);+ recoveredCount++;+ }++ return recoveredCount;+ }+/*** Retries overdue pending webhook deliveries with atomic claim & exponential backoff.* Backoff strategy: 5s, 30s, 2m, 10m, 1h*/async retryPending() {+ // Ensure any terminal session whose dispatch() was skipped before creating a row is backfilled first.+ try {+ this.recoverMissingDeliveries({ resetInFlight: false });+ } catch {}+const nowIso = new Date().toISOString();// Invariant: Atomically claim overdue pending deliveries in a transaction to prevent duplicate dispatches