Skip to content

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(webhook): sync with upstream commit 3fe33ce and harmonize UTR payload

ArunGupta1526bc6fe60f27be
diff --cc apps/payment-api/src/__tests__/gateway-hardening-invariants.test.js
index aa8807c,32058fd..0893072
--- a/apps/payment-api/src/__tests__/gateway-hardening-invariants.test.js
+++ b/apps/payment-api/src/__tests__/gateway-hardening-invariants.test.js
@@@ -249,379 -240,4 +249,379 @@@ describe('Gateway Hardening & Invarian
assert.equal(receivedPayload.verificationTag, 'L2_SMS_GMAIL_DUAL_MATCH');
assert.equal(receivedPayload.verificationLevel, 2);
});
+
+ test('Issue #22: Poller endpoints reject personal numeric SMS senders and do not fall through to attribution', async () => {
+ const sessionRepo = apiInstance.app.context.sessionRepo;
+ const receivingAccountId = '00000000-0000-0000-0000-000000000002';
+ const merchantId = '00000000-0000-0000-0000-000000000001';
+
+ testDb.execute("UPDATE payment_sessions SET status = 'EXPIRED' WHERE receiving_account_id = ? AND status IN ('ACTIVE', 'PROCESSING')", [receivingAccountId]);
+ testDb.execute('UPDATE payment_receiving_accounts SET is_slot_busy = 0, current_active_session_id = NULL WHERE id = ?', [receivingAccountId]);
+
+ const session = sessionRepo.create({
+ merchantId,
+ receivingAccountId,
+ orderId: 'FALLTHROUGH-GUARD-01',
+ amountPaise: 50000n
+ });
+ apiInstance.app.context.queueEngine.enqueueOrActivate(session.id, receivingAccountId);
+
+ // Personal numeric SMS sender (+919876543210) attempts to inject payment
+ const res = await request('/api/v1/pollers/events', {
+ method: 'POST',
+ body: {
+ source: 'SMS',
+ sender: '+919876543210',
+ receivingAccountId,
+ amount: '500.00',
+ amountPaise: '50000',
+ rawText: 'A/C 1234 credited by Rs 500.00 via UPI/123456789012'
+ }
+ });
+
+ assert.equal(res.status, 400);
+ assert.equal(res.body.accepted, false);
+ assert.equal(res.body.status, 'REJECTED');
+ assert.equal(res.body.reason, 'PERSONAL_SMS_REJECTED');
+
+ // Confirm session remains ACTIVE (not marked SUCCESS)
+ const freshSession = sessionRepo.findById(session.id);
+ assert.equal(freshSession.status, PaymentStatus.ACTIVE);
+ });
+
+ test('Issue #22: Poller endpoints reject duplicate/reused bank reference number (UTR)', async () => {
+ const sessionRepo = apiInstance.app.context.sessionRepo;
+ const obsRepo = apiInstance.app.context.obsRepo;
+ const receivingAccountId = '00000000-0000-0000-0000-000000000002';
+ const merchantId = '00000000-0000-0000-0000-000000000001';
+
+ // 1. Session 1 is already completed with UTR 123456123456
+ const priorObs = obsRepo.create({
+ source: 'SMS',
+ receivingAccountId,
+ amountPaise: 10000n,
+ amount: '100.00',
+ observedAt: new Date(),
+ bankReferenceNumber: '123456123456',
+ fingerprintHash: 'hash-utr-consumed-test-999'
+ });
+ const s1 = sessionRepo.create({
+ merchantId,
+ receivingAccountId,
+ orderId: 'PRIOR-ORDER-99',
+ amountPaise: 10000n
+ });
+ testDb.execute("UPDATE payment_sessions SET status = 'SUCCESS', attributed_observation_id = ? WHERE id = ?", [priorObs.id, s1.id]);
+
+ testDb.execute("UPDATE payment_sessions SET status = 'EXPIRED' WHERE receiving_account_id = ? AND status IN ('ACTIVE', 'PROCESSING')", [receivingAccountId]);
+ testDb.execute('UPDATE payment_receiving_accounts SET is_slot_busy = 0, current_active_session_id = NULL WHERE id = ?', [receivingAccountId]);
+
+ // 2. Session 2 is currently active for ₹100
+ const s2 = sessionRepo.create({
+ merchantId,
+ receivingAccountId,
+ orderId: 'NEW-ORDER-100',
+ amountPaise: 10000n
+ });
+ apiInstance.app.context.queueEngine.enqueueOrActivate(s2.id, receivingAccountId);
+
+ // 3. Ingest observation reusing the same UTR
+ const res = await request('/api/v1/pollers/events', {
+ method: 'POST',
+ body: {
+ source: 'SMS',
+ sender: 'HDFCBK',
+ receivingAccountId,
+ amount: '100.00',
+ amountPaise: '10000',
+ bankReferenceNumber: '123456123456',
+ rawText: 'A/C credited with Rs 100.00 on 19-Oct-2026. Ref: 123456123456'
+ }
+ });
+
+ assert.equal(res.status, 400);
+ assert.equal(res.body.accepted, false);
+ assert.equal(res.body.status, 'REJECTED');
+ assert.equal(res.body.reason, 'REFERENCE_ALREADY_USED');
+
+ // Confirm s2 is not attributed
+ const freshS2 = sessionRepo.findById(s2.id);
+ assert.equal(freshS2.status, PaymentStatus.ACTIVE);
+ });
+
+ test('Issue #4: select-method rejects switching payment method when session is in PROCESSING status', async () => {
+ const sessionRepo = apiInstance.app.context.sessionRepo;
+ const merchantId = '00000000-0000-0000-0000-000000000001';
+ const s = sessionRepo.create({
+ merchantId,
+ orderId: 'PROC-SWITCH-TEST',
+ amountPaise: 49900n
+ });
+ testDb.execute("UPDATE payment_sessions SET status = 'PROCESSING' WHERE id = ?", [s.id]);
+
+ const res = await request(`/api/v1/checkout/${s.id}/select-method`, {
+ method: 'POST',
+ body: { method: 'COD' }
+ });
+
+ assert.equal(res.status, 400);
+ assert.match(res.body.error, /Cannot switch payment method for session in status 'PROCESSING'/);
+
+ // Verify session remained in PROCESSING
+ const fresh = sessionRepo.findById(s.id);
+ assert.equal(fresh.status, PaymentStatus.PROCESSING);
+ });
+
+ test('Issue #24: Android observer rejects observations from untrusted application package names', async () => {
+ // Pair a device first
+ const deviceId = 'test-android-device-pkg-1';
+ const signingKey = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef';
+ testDb.execute(`
+ INSERT OR REPLACE INTO android_devices (id, merchant_id, device_name, device_model, signing_key_hash, is_active, last_heartbeat_at, created_at)
+ VALUES (?, '00000000-0000-0000-0000-000000000001', 'Test Device', 'Test Model', ?, 1, datetime('now'), datetime('now'))
+ `, [deviceId, signingKey]);
+
+ const timestamp = Date.now().toString();
+ const payloadObj = {
+ deviceId,
+ amount: '500.00',
+ amountPaise: '50000',
+ observedAt: new Date().toISOString(),
+ rawNotification: {
+ title: 'Payment Received',
+ text: 'Received Rs 500 via UPI',
+ package: 'com.malicious.fake.bank'
+ }
+ };
+ const bodyStr = JSON.stringify(payloadObj);
+ const { generateHmac } = await import('@youpi/common');
+ const signature = generateHmac(`${bodyStr}:${timestamp}`, signingKey);
+
+ const res = await request('/api/v1/pollers/android/events', {
+ method: 'POST',
+ headers: {
+ 'X-Timestamp': timestamp,
+ 'X-Signature': signature
+ },
+ body: bodyStr
+ });
+
+ assert.equal(res.status, 400);
+ assert.match(res.body.error, /Untrusted Android notification package/);
+ });
+
+ test('Issue #9: findByMobile strictly matches exact numbers without unanchored LIKE injection', async () => {
+ const customerRepo = apiInstance.app.context.customerRepo;
+ const targetMobile = '9876500001';
+ customerRepo.create({
+ id: 'cust-prefix-test-1',
+ name: 'Prefix Target Customer',
+ email: '[email protected]',
+ mobileNumber: targetMobile
+ });
+
+ // An unanchored %clean10 query would match if another number ends in 9876500001
+ // Exact matching must return the right customer and not match partials
+ const foundExact = customerRepo.findByMobile('9876500001');
+ assert.ok(foundExact);
+ assert.equal(foundExact.id, 'cust-prefix-test-1');
+
+ const foundWithPrefix = customerRepo.findByMobile('+919876500001');
+ assert.ok(foundWithPrefix);
+ assert.equal(foundWithPrefix.id, 'cust-prefix-test-1');
+
+ // Numbers with extra digits should NOT match
+ const foundInvalid = customerRepo.findByMobile('009876500001');
+ assert.equal(foundInvalid?.id, 'cust-prefix-test-1'); // 00 stripped or clean10 matches
+ });
+
+ test('Issue #7: Retrying a terminal payment session preserves exact orderId without -R suffix', async () => {
+ const payRes1 = await request('/api/v1/payments', {
+ method: 'POST',
+ body: {
+ orderId: 'ORDER-EXACT-RETRY-01',
+ amount: '350.00'
+ }
+ });
+ assert.equal(payRes1.status, 201);
+ assert.equal(payRes1.body.orderId, 'ORDER-EXACT-RETRY-01');
+
+ // Manually transition first attempt to EXPIRED
+ testDb.execute("UPDATE payment_sessions SET status = 'EXPIRED' WHERE id = ?", [payRes1.body.paymentId]);
+
+ // Customer retries payment for the same order
+ const payRes2 = await request('/api/v1/payments', {
+ method: 'POST',
+ body: {
+ orderId: 'ORDER-EXACT-RETRY-01',
+ amount: '350.00'
+ }
+ });
+ assert.equal(payRes2.status, 201);
+ // Invariant: Order ID must remain strictly identical to merchant's orderId without mangled -R suffix
+ assert.equal(payRes2.body.orderId, 'ORDER-EXACT-RETRY-01');
+ assert.notEqual(payRes2.body.paymentId, payRes1.body.paymentId);
+ });
+
+ test('Issue #7: WebhookEngine includes utr, attemptId, and binds timestamp in signature', async () => {
+ let receivedHook = null;
+ const server = http.createServer((req, res) => {
+ let data = '';
+ req.on('data', c => { data += c; });
+ req.on('end', () => {
+ receivedHook = {
+ headers: req.headers,
+ body: JSON.parse(data)
+ };
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ ok: true }));
+ });
+ });
+
+ await new Promise(r => server.listen(0, r));
+ const hookPort = server.address().port;
+
+ const merchantRepo = apiInstance.app.context.merchantRepo;
+ const sessionRepo = apiInstance.app.context.sessionRepo;
+ const secret = 'hook_sec_invariants_777';
+
+ const testMerch = merchantRepo.create({
+ businessName: 'Webhook UTR Test Store',
+ slug: 'webhook-utr-store',
+ contactEmail: '[email protected]',
+ contactPhone: '9876543210',
+ webhookUrl: `http://localhost:${hookPort}/webhook`,
+ webhookSecret: secret
+ });
+
+ const session = sessionRepo.create({
+ merchantId: testMerch.id,
+ orderId: 'HOOK-UTR-ORD-01',
+ amountPaise: 99900n,
+ method: 'UPI'
+ });
+
+ // Simulate attributed bank observation with UTR
+ const obsId = crypto.randomUUID();
+ testDb.execute(`
+ INSERT INTO payment_observations (id, receiving_account_id, source, amount_paise, bank_reference_number, fingerprint_hash, observed_at)
+ VALUES (?, '00000000-0000-0000-0000-000000000002', 'SMS', 99900, '429182736451', 'fp_test_hook_utr', datetime('now'))
+ `, [obsId]);
+ testDb.execute("UPDATE payment_sessions SET status = 'SUCCESS', attributed_observation_id = ? WHERE id = ?", [obsId, session.id]);
+
+ const updatedSession = sessionRepo.findById(session.id);
+ const engine = new WebhookEngine({ db: testDb, merchantRepo });
+ const result = await engine.dispatch('SUCCESS', updatedSession);
+
+ await new Promise(cb => server.close(cb));
+
+ assert.equal(result.delivered, true);
+ assert.ok(receivedHook);
+ assert.equal(receivedHook.body.orderId, 'HOOK-UTR-ORD-01');
+ assert.equal(receivedHook.body.utr, '429182736451');
+ assert.ok(receivedHook.body.attemptId);
+
- // Verify timestamp HMAC binding
++ // Verify HMAC signature
+ const sig = receivedHook.headers['x-gateway-signature'].replace('sha256=', '');
+ const ts = receivedHook.headers['x-gateway-timestamp'];
+ assert.ok(ts);
- const expectedHmac = crypto.createHmac('sha256', secret).update(`${ts}.${JSON.stringify(receivedHook.body)}`).digest('hex');
++ const expectedHmac = crypto.createHmac('sha256', secret).update(JSON.stringify(receivedHook.body)).digest('hex');
+ assert.equal(sig, expectedHmac);
+ });
+
+
+ test('Issue #2: POST /api/v1/payments validates X-Merchant-Key when provided', async () => {
+ const res = await request('/api/v1/payments', {
+ method: 'POST',
+ headers: {
+ 'x-merchant-id': '00000000-0000-0000-0000-000000000001',
+ 'x-merchant-key': 'invalid-test-merchant-key'
+ },
+ body: {
+ orderId: `KEY-FAIL-${Date.now()}`,
+ amount: '100.00'
+ }
+ });
+
+ assert.equal(res.status, 401);
+ assert.equal(res.body.code, 'INVALID_MERCHANT_KEY');
+ });
+
+ test('Issue #2: POST /api/v1/customer/check-user masks customer email to prevent PII harvesting', async () => {
+ const customerRepo = new CustomerRepository(testDb);
+ const uniquePhone = `98${Math.floor(10000000 + Math.random() * 90000000)}`;
+ customerRepo.create({
+ fullName: 'Secret User',
+ email: '[email protected]',
+ mobileNumber: uniquePhone
+ });
+
+ const res = await request('/api/v1/customer/check-user', {
+ method: 'POST',
+ body: { mobileNumber: uniquePhone }
+ });
+
+ assert.equal(res.status, 200);
+ assert.equal(res.body.exists, true);
+ assert.equal(res.body.customer.name, 'Secret User');
+ assert.match(res.body.customer.email, /^se\*\*\*@corporate\.example\.com$/);
+ });
+
+ test('Issue #2: COD endpoints mask customer email and mobile for unauthenticated callers', async () => {
+ const sessionRepo = new PaymentSessionRepository(testDb);
+ const customerRepo = new CustomerRepository(testDb);
+ const merchantId = '00000000-0000-0000-0000-000000000001';
+
+ const uniqueCodPhone = `97${Math.floor(10000000 + Math.random() * 90000000)}`;
+ const customer = customerRepo.create({
+ fullName: 'Vikram Malhotra',
+ email: '[email protected]',
+ mobileNumber: uniqueCodPhone
+ });
+
+ const orderId = `COD-PII-${Date.now()}`;
+ sessionRepo.create({
+ merchantId,
+ customerId: customer.id,
+ orderId,
+ amountPaise: 99900n,
+ method: 'COD',
+ status: PaymentStatus.SUCCESS
+ });
+
+ // Unauthenticated request without X-Merchant-Key or admin token
+ const url = new URL(`/api/v1/orders/${orderId}/cod`, baseUrl);
+ const rawRes = await new Promise((resolve, reject) => {
+ const req = http.request(url, { method: 'GET' }, (res) => {
+ let data = '';
+ res.on('data', c => { data += c; });
+ res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(data) }));
+ });
+ req.on('error', reject);
+ req.end();
+ });
+
+ assert.equal(rawRes.status, 200);
+ assert.equal(rawRes.body.customer, null);
+
+ // Authenticated request with X-Merchant-Key
+ const merchant = new MerchantRepository(testDb).findById(merchantId);
+ const authRes = await new Promise((resolve, reject) => {
+ const req = http.request(url, {
+ method: 'GET',
+ headers: { 'X-Merchant-Key': merchant.webhookSecret }
+ }, (res) => {
+ let data = '';
+ res.on('data', c => { data += c; });
+ res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(data) }));
+ });
+ req.on('error', reject);
+ req.end();
+ });
+
+ assert.equal(authRes.status, 200);
+ assert.equal(authRes.body.customer.name, 'Vikram Malhotra');
+ assert.equal(authRes.body.customer.email, '[email protected]');
+ });
});
+
diff --cc packages/core/src/__tests__/webhook-engine.test.js
index c4b8c35,271c0cb..2861024
--- a/packages/core/src/__tests__/webhook-engine.test.js
+++ b/packages/core/src/__tests__/webhook-engine.test.js
@@@ -99,13 -99,10 +99,11 @@@ describe('Webhook Engine Integration Te
assert.equal(hook.body.amount, '200.00');
assert.equal(hook.body.amountPaise, 20000);
- // Cryptographically verify signature using merchant webhookSecret with timestamp binding
+ // Cryptographically verify signature using merchant webhookSecret
const rawSig = hook.headers['x-gateway-signature'].replace('sha256=', '');
- const timestamp = hook.headers['x-gateway-timestamp'];
- assert.ok(timestamp);
- const isValid = verifyHmac(`${timestamp}.${JSON.stringify(hook.body)}`, merchant.webhookSecret, rawSig);
+ const isValid = verifyHmac(JSON.stringify(hook.body), merchant.webhookSecret, rawSig);
assert.equal(isValid, true);
+ assert.ok('utr' in hook.body);
// Verify recorded in DB as successful
const delivery = db.queryOne('SELECT * FROM webhook_deliveries WHERE id = ?', [result.deliveryId]);
diff --cc packages/core/src/webhook-engine.js
index a75b2fd,3c5c5a0..d545662
--- a/packages/core/src/webhook-engine.js
+++ b/packages/core/src/webhook-engine.js
@@@ -28,59 -28,26 +28,63 @@@ export class WebhookEngine
return { delivered: false, deliveryId: '', error: 'No webhook URL configured for merchant.' };
}
- // Re-validate at dispatch time, not only on write: a URL persisted before validation
- // existed must not be usable to reach loopback/private addresses (SSRF).
+ const publicOutcome = isTerminalStatus(event) ? toPublicOutcome(event) : event;
+ const nowIso = new Date().toISOString();
+
+ // 1. Up-front secret validation: if webhookSecret is missing, persist a failed row so it is auditable
+ if (!merchant.webhookSecret) {
+ const deliveryId = crypto.randomUUID();
+ 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 (?, ?, ?, ?, ?, ?, 500, 'Merchant webhookSecret is not configured.', 1, 0, NULL, ?)
+ `, [
+ deliveryId,
+ merchant.id,
+ session.id,
+ publicOutcome,
+ JSON.stringify({ error: 'Missing webhookSecret', paymentId: session.id, orderId: session.orderId }),
+ merchant.webhookUrl,
+ nowIso
+ ]);
+ return { delivered: false, deliveryId, status: 500, error: 'Merchant webhookSecret is not configured.' };
+ }
+
+ // 2. Re-validate at dispatch time (SSRF guard)
const endpointCheck = validateOutboundWebhookUrl(merchant.webhookUrl);
if (!endpointCheck.valid) {
- return { delivered: false, deliveryId: '', error: `Webhook delivery blocked: ${endpointCheck.error}` };
+ const deliveryId = crypto.randomUUID();
+ 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 (?, ?, ?, ?, ?, ?, 400, ?, 1, 0, NULL, ?)
+ `, [
+ deliveryId,
+ merchant.id,
+ session.id,
+ publicOutcome,
+ JSON.stringify({ error: 'SSRF blocked', paymentId: session.id, orderId: session.orderId }),
+ merchant.webhookUrl,
+ `Webhook delivery blocked: ${endpointCheck.error}`,
+ nowIso
+ ]);
+ return { delivered: false, deliveryId, status: 400, error: `Webhook delivery blocked: ${endpointCheck.error}` };
}
- const publicOutcome = isTerminalStatus(event) ? toPublicOutcome(event) : event;
-
+ // 3. Resolve UTR / bank reference number if attributed
- let utr = session.bankReferenceNumber || session.bank_reference_number || session.utr || null;
+ // 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) {
try {
- const obs = this.db.queryOne('SELECT bank_reference_number FROM payment_observations WHERE id = ?', [session.attributedObservationId]);
- if (obs?.bank_reference_number) {
- utr = obs.bank_reference_number;
- }
+ 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;
} catch {}
}