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): complete gateway state machine hardening, webhook retries and PII masking (#2, #4, #7, #9, #24, #28)
ArunGupta1526954d8bd36fe1
diff --git a/apps/android-observer-app/app/src/main/java/com/youpi/observer/PaymentNotificationListenerService.java b/apps/android-observer-app/app/src/main/java/com/youpi/observer/PaymentNotificationListenerService.javaindex e0b7d03..e662eaf 100644--- a/apps/android-observer-app/app/src/main/java/com/youpi/observer/PaymentNotificationListenerService.java+++ b/apps/android-observer-app/app/src/main/java/com/youpi/observer/PaymentNotificationListenerService.java@@ -6,6 +6,9 @@ import android.service.notification.NotificationListenerService;import android.service.notification.StatusBarNotification;import android.util.Log;+import java.util.Arrays;+import java.util.HashSet;+import java.util.Set;import java.util.regex.Matcher;import java.util.regex.Pattern;@@ -13,6 +16,33 @@ public class PaymentNotificationListenerService extends NotificationListenerServprivate static final String TAG = "YoupiNotifListener";private ApiClient apiClient;+ private static final Set<String> ALLOWED_BANKING_PACKAGES = new HashSet<>(Arrays.asList(+ "com.google.android.apps.nbu.paisa.user",+ "com.phonepe.app",+ "net.one97.paytm",+ "in.org.npci.upiapp",+ "in.amazon.mShop.android.shopping",+ "com.dreamplug.androidapp",+ "com.freecharge.android",+ "com.mobikwik_new",+ "com.fampay.in",+ "com.sbi.upi",+ "com.sbi.lotusintouch",+ "com.hdfcbank.payzapp",+ "com.snapwork.hdfc",+ "com.csam.icici.bank.imobile",+ "com.axis.mobile",+ "com.msf.kbank.mobile",+ "com.bankofbaroda.mconnect",+ "com.idfcfirstbank.optimus",+ "com.infrasofttech.indianbank",+ "com.canarabank.mobility",+ "com.infrasoft.uboi",+ "com.fedmobile",+ "com.google.android.apps.messaging",+ "com.samsung.android.messaging"+ ));+private static final Pattern AMOUNT_PATTERN = Pattern.compile("(?:Rs\\.?|INR|₹)\\s*([0-9,]+(?:\\.[0-9]{1,2})?)", Pattern.CASE_INSENSITIVE);private static final Pattern UTR_PATTERN = Pattern.compile("(?:UPI\\s*(?:ref|reference|txn|id)?|Ref(?:erence)?\\s*(?:no|number)?|UTR)\\s*[:#-]?\\s*([0-9]{12})", Pattern.CASE_INSENSITIVE);private static final Pattern VPA_PATTERN = Pattern.compile("([a-zA-Z0-9._-]+@[a-zA-Z0-9]+)");@@ -27,6 +57,12 @@ public class PaymentNotificationListenerService extends NotificationListenerServpublic void onNotificationPosted(StatusBarNotification sbn) {if (sbn == null || !apiClient.isPaired()) return;+ // Security Invariant (Issue #24): Strictly discard notifications originating from unverified apps+ final String pkgName = sbn.getPackageName();+ if (pkgName == null || !ALLOWED_BANKING_PACKAGES.contains(pkgName)) {+ return;+ }+Notification notif = sbn.getNotification();if (notif == null) return;@@ -77,13 +113,14 @@ public class PaymentNotificationListenerService extends NotificationListenerServfinal String finalVpa = vpa;final String finalTitle = title;final String finalTex = text;+ final String finalPkg = pkgName;- Log.i(TAG, "Captured UPI credit notification: ₹" + amount + " UTR: " + bankRef);+ Log.i(TAG, "Captured UPI credit notification: ₹" + amount + " UTR: " + bankRef + " from pkg: " + pkgName);new Thread(new Runnable() {@Overridepublic void run() {- apiClient.sendObservation(amountPaise, finalAmount, finalBankRef, finalVpa, finalTitle, finalTex);+ apiClient.sendObservation(amountPaise, finalAmount, finalBankRef, finalVpa, finalTitle, finalTex, finalPkg);}}).start();}diff --git a/apps/payment-api/src/__tests__/gateway-hardening-invariants.test.js b/apps/payment-api/src/__tests__/gateway-hardening-invariants.test.jsindex 32058fd..0bc1c3a 100644--- a/apps/payment-api/src/__tests__/gateway-hardening-invariants.test.js+++ b/apps/payment-api/src/__tests__/gateway-hardening-invariants.test.js@@ -2,11 +2,20 @@ import '../../../../scripts/test-support.js';import { test, describe, before, after } from 'node:test';import assert from 'node:assert/strict';import http from 'node:http';+import crypto from 'node:crypto';+import fs from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';import { Database } from '@youpi/db';import { startServer as startPaymentApi } from '../index.js';import { PaymentStatus, PaymentMethod } from '@youpi/common';import { authHeadersFor } from '../../../../scripts/test-support.js';import { WebhookEngine } from '@youpi/core';+import { PaymentSessionRepository, CustomerRepository } from '@youpi/db';++const __filename = fileURLToPath(import.meta.url);+const __dirname = path.dirname(__filename);+const rootDir = path.resolve(__dirname, '../../../..');describe('Gateway Hardening & Invariant Protection Test Suite (#23, #25, #26, #27, #28)', () => {let apiInstance;@@ -240,4 +249,362 @@ describe('Gateway Hardening & Invariant Protection Test Suite (#23, #25, #26, #2assert.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+ 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');+ 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_secret_key_123'+ },+ 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.name, 'Vikram Malhotra');+ assert.match(rawRes.body.customer.email, /^vi\*\*\*@testmail\.com$/);+ assert.match(rawRes.body.customer.mobileNumber, /^97\*\*\*\*\*\*\d{2}$/);+ });});+diff --git a/apps/payment-api/src/__tests__/payment-api.test.js b/apps/payment-api/src/__tests__/payment-api.test.jsindex 3abce31..3529b05 100644--- a/apps/payment-api/src/__tests__/payment-api.test.js+++ b/apps/payment-api/src/__tests__/payment-api.test.js@@ -658,13 +658,15 @@ describe('Payment API End-to-End HTTP Integration Tests', () => {assert.equal(parsedBody.orderId, 'WEBHOOK-TEST-ORD-1');assert.equal(parsedBody.amount, '450.00');- // 10. Cryptographically verify signature using the custom secret+ // 10. Cryptographically verify signature using the custom secret with timestamp bindingconst sig = receivedHeaders['x-gateway-signature'].replace('sha256=', '');- const validSig = verifyHmac(receivedPayload, customSecret, sig);+ const ts = receivedHeaders['x-gateway-timestamp'];+ assert.ok(ts);+ const validSig = verifyHmac(`${ts}.${receivedPayload}`, customSecret, sig);assert.equal(validSig, true);// Verify wrong secret fails- const invalidSig = verifyHmac(receivedPayload, 'wrong_secret_123', sig);+ const invalidSig = verifyHmac(`${ts}.${receivedPayload}`, 'wrong_secret_123', sig);assert.equal(invalidSig, false);// 11. Test non-destructive update: update only businessName and verify webhook config is preserved!diff --git a/apps/payment-api/src/index.js b/apps/payment-api/src/index.jsindex 867ff00..ac0d43e 100644--- a/apps/payment-api/src/index.js+++ b/apps/payment-api/src/index.js@@ -103,7 +103,8 @@ export function createPaymentApp(customDb = null, options = {}) {accountRepo,queueEngine,timingEngine,- auditRepo+ auditRepo,+ eventEmitter});const webhookEngine = new WebhookEngine({@@ -302,25 +303,35 @@ export function createPaymentApp(customDb = null, options = {}) {// Sweep expired ACTIVE sessionsconst expiredActive = db.query(`- SELECT id, receiving_account_id FROM payment_sessions+ SELECT id, merchant_id, order_id, receiving_account_id FROM payment_sessionsWHERE status = 'ACTIVE' AND expires_at <= ?`, [nowIso]);for (const row of expiredActive) {sessionRepo.transitionToTerminal(row.id, PaymentStatus.EXPIRED);server.broadcastSse(row.id, 'status_change', { status: PaymentStatus.EXPIRED });+ eventEmitter.emit('PAYMENT.EXPIRED', {+ paymentId: row.id,+ orderId: row.order_id,+ merchantId: row.merchant_id+ });handleSlotFreedAndPromote(row.receiving_account_id);}// Sweep failed PROCESSING sessionsconst failedProc = db.query(`- SELECT id, receiving_account_id FROM payment_sessions+ SELECT id, merchant_id, order_id, receiving_account_id FROM payment_sessionsWHERE status = 'PROCESSING' AND processing_expires_at <= ?`, [nowIso]);for (const row of failedProc) {sessionRepo.transitionToTerminal(row.id, PaymentStatus.FAILED);server.broadcastSse(row.id, 'status_change', { status: PaymentStatus.FAILED });+ eventEmitter.emit('PAYMENT.FAILED', {+ paymentId: row.id,+ orderId: row.order_id,+ merchantId: row.merchant_id+ });handleSlotFreedAndPromote(row.receiving_account_id);}@@ -338,6 +349,13 @@ export function createPaymentApp(customDb = null, options = {}) {if (queueSyncDaemon.unref) queueSyncDaemon.unref();+ // Continuous Recurring Webhook Retry Daemon (Sweeps and dispatches pending webhook deliveries every 5s)+ const webhookRetryDaemon = setInterval(() => {+ webhookEngine.retryPending().catch(() => {});+ }, Number(process.env.WEBHOOK_RETRY_INTERVAL_MS || 5000));++ if (webhookRetryDaemon.unref) webhookRetryDaemon.unref();+// Continuous 1-Second Aggressive Polling Daemon across SMS Gateway & Gmail Observersconst aggressivePollerDaemon = setInterval(async () => {try {@@ -446,6 +464,7 @@ export function createPaymentApp(customDb = null, options = {}) {function destroy() {clearInterval(queueSyncDaemon);clearInterval(aggressivePollerDaemon);+ clearInterval(webhookRetryDaemon);for (const timer of activeSweepTimers) {clearInterval(timer);}@@ -454,6 +473,9 @@ export function createPaymentApp(customDb = null, options = {}) {if (typeof attributionEngine.destroy === 'function') {attributionEngine.destroy();}+ if (whatsappBerryService && typeof whatsappBerryService.disconnect === 'function') {+ whatsappBerryService.disconnect({ cleanSession: false }).catch(() => {});+ }}return {diff --git a/apps/payment-api/src/routes/admin.routes.js b/apps/payment-api/src/routes/admin.routes.jsindex 1bded92..eab105f 100644--- a/apps/payment-api/src/routes/admin.routes.js+++ b/apps/payment-api/src/routes/admin.routes.js@@ -178,20 +178,26 @@ export function registerAdminRoutes(server, ctx) {});// Query live Google Messages browser automator status- let smsStatus = { status: 'STANDBY', isPaired: false, messagesObserved: 0 };+ let smsStatus = { status: 'STANDBY', isPaired: false, messagesObserved: 0, isRunning: false };try {const smsPort = Number(process.env.SMS_OBSERVER_PORT || 6002);- const smsRes = await fetch(`http://localhost:${smsPort}/api/browser/status`, { signal: AbortSignal.timeout(1500) });+ const smsRes = await fetch(`http://localhost:${smsPort}/api/browser/status`, {+ headers: { Authorization: `Bearer ${getObserverToken()}` },+ signal: AbortSignal.timeout(1500)+ });if (smsRes.ok) {smsStatus = await smsRes.json();}} catch {}// Query live Gmail browser automator status- let gmailStatus = { status: 'STANDBY', isLoggedIn: false, emailsObserved: 0 };+ let gmailStatus = { status: 'STANDBY', isLoggedIn: false, emailsObserved: 0, isRunning: false };try {const gmailPort = Number(process.env.GMAIL_OBSERVER_PORT || 6003);- const gmailRes = await fetch(`http://localhost:${gmailPort}/api/browser/status`, { signal: AbortSignal.timeout(1500) });+ const gmailRes = await fetch(`http://localhost:${gmailPort}/api/browser/status`, {+ headers: { Authorization: `Bearer ${getObserverToken()}` },+ signal: AbortSignal.timeout(1500)+ });if (gmailRes.ok) {gmailStatus = await gmailRes.json();}@@ -201,6 +207,7 @@ export function registerAdminRoutes(server, ctx) {gmail: {status: gmailStatus.status || (gmailStatus.isLoggedIn ? 'CONNECTED' : 'STANDBY'),isLoggedIn: Boolean(gmailStatus.isLoggedIn),+ isRunning: Boolean(gmailStatus.isRunning || gmailStatus.isLoggedIn || gmailStatus.status === 'CONNECTED'),emailsObserved: gmailStatus.emailsObserved || 0,lastCheckedAt: gmailStatus.lastCheckedAt || null},@@ -211,6 +218,7 @@ export function registerAdminRoutes(server, ctx) {sms: {status: smsStatus.status || (smsStatus.isPaired ? 'CONNECTED' : 'STANDBY'),isPaired: Boolean(smsStatus.isPaired),+ isRunning: Boolean(smsStatus.isRunning || smsStatus.isPaired || smsStatus.status === 'CONNECTED'),messagesObserved: smsStatus.messagesObserved || 0,lastSeenAt: smsStatus.lastSeenAt || null}diff --git a/apps/payment-api/src/routes/checkout.routes.js b/apps/payment-api/src/routes/checkout.routes.jsindex 8658815..9e2c09c 100644--- a/apps/payment-api/src/routes/checkout.routes.js+++ b/apps/payment-api/src/routes/checkout.routes.js@@ -1019,8 +1019,8 @@ export function registerCheckoutRoutes(server, ctx) {return;}- if ([PaymentStatus.SUCCESS, PaymentStatus.FAILED, PaymentStatus.EXPIRED, PaymentStatus.CANCELLED].includes(session.status)) {- HttpServer.json(res, 400, { error: `Cannot switch payment method for terminal session in status '${session.status}'` });+ if ([PaymentStatus.SUCCESS, PaymentStatus.FAILED, PaymentStatus.EXPIRED, PaymentStatus.CANCELLED, PaymentStatus.PROCESSING].includes(session.status)) {+ HttpServer.json(res, 400, { error: `Cannot switch payment method for session in status '${session.status}'` });return;}@@ -1283,8 +1283,8 @@ export function registerCheckoutRoutes(server, ctx) {ctx.sessionRepo.db.execute(`UPDATE payment_receiving_accountsSET is_slot_busy = 0, current_active_session_id = NULL, updated_at = ?- WHERE id = ?- `, [nowIso, oldReceivingAccountId]);+ WHERE id = ? AND current_active_session_id = ?+ `, [nowIso, oldReceivingAccountId, session.id]);const promoted = ctx.queueEngine.promoteNext(oldReceivingAccountId);if (promoted) {@@ -1649,10 +1649,8 @@ export function registerCheckoutRoutes(server, ctx) {}}- // 4. Generate unique order reference from sourceSession- const cleanOrderId = sourceSession.orderId ? sourceSession.orderId.replace(/-R\d+$/, '') : `ORD-${Date.now()}`;- const randSuffix = Math.floor(1000 + Math.random() * 9000);- const newOrderId = `${cleanOrderId}-R${randSuffix}`;+ // 4. Preserve merchant's exact order reference from sourceSession+ const newOrderId = sourceSession.orderId ? sourceSession.orderId.replace(/-R\d+$/, '') : `ORD-${Date.now()}`;// 5. Ensure device exists and registerif (newDeviceId && ctx.deviceRepo) {diff --git a/apps/payment-api/src/routes/customer.routes.js b/apps/payment-api/src/routes/customer.routes.jsindex c5e8166..c46b971 100644--- a/apps/payment-api/src/routes/customer.routes.js+++ b/apps/payment-api/src/routes/customer.routes.js@@ -34,7 +34,8 @@ export function registerCustomerRoutes(server, ctx) {// Helper to set session cookie headerfunction buildSessionCookie(token, maxAgeSeconds = 30 * 24 * 3600) {- return `youpi_session=${token}; Path=/; Max-Age=${maxAgeSeconds}; HttpOnly; SameSite=Lax`;+ const isProd = process.env.NODE_ENV === 'production';+ return `youpi_session=${token}; Path=/; Max-Age=${maxAgeSeconds}; HttpOnly; SameSite=Lax${isProd ? '; Secure' : ''}`;}// Pending signup challenges cache: mobileNumber -> { otpCode, expiresAt, name, email }@@ -43,6 +44,9 @@ export function registerCustomerRoutes(server, ctx) {// Throttles OTP dispatch per mobile number so the WhatsApp channel cannot be flooded/cost-abused.const otpRequestLog = new Map();+ // Throttles check-user inquiries to prevent bulk mobile number scanning / user enumeration.+ const checkUserRateMap = new Map();+/*** Resolves the configured cooldown between consecutive OTP dispatches.* Prioritizes explicit runtime options (ctx.otpCooldownMs), environment overrides@@ -112,6 +116,18 @@ export function registerCustomerRoutes(server, ctx) {return;}+ const ip = req.socket?.remoteAddress || '127.0.0.1';+ const now = Date.now();+ for (const [key, at] of checkUserRateMap) {+ if (now - at > 60000) checkUserRateMap.delete(key);+ }+ const ipCount = Array.from(checkUserRateMap.entries()).filter(([k]) => k.startsWith(ip)).length;+ if (ipCount >= 60) {+ HttpServer.json(res, 429, { error: 'Too many requests. Please try again in a minute.' });+ return;+ }+ checkUserRateMap.set(`${ip}_${cleanMobile}_${now}`, now);+const existingUser = ctx.customerRepo.findByMobile(cleanMobile);HttpServer.json(res, 200, {@@ -121,8 +137,8 @@ export function registerCustomerRoutes(server, ctx) {customer: existingUser ? {id: existingUser.id,name: existingUser.name,- email: existingUser.email,- mobileNumber: existingUser.mobileNumber+ email: existingUser.email ? `${existingUser.email.slice(0, 2)}***@${existingUser.email.split('@')[1] || '***'}` : null,+ mobileNumber: cleanMobile} : null});});diff --git a/apps/payment-api/src/routes/payments.routes.js b/apps/payment-api/src/routes/payments.routes.jsindex 1a63fdf..13e7323 100644--- a/apps/payment-api/src/routes/payments.routes.js+++ b/apps/payment-api/src/routes/payments.routes.js@@ -67,6 +67,13 @@ export function registerPaymentRoutes(server, ctx) {return;}+ if (req.headers['x-merchant-key']) {+ if (!merchant.webhookSecret || !safeEqual(req.headers['x-merchant-key'].trim(), merchant.webhookSecret)) {+ HttpServer.json(res, 401, { error: 'Invalid merchant key', code: 'INVALID_MERCHANT_KEY' });+ return;+ }+ }+if (!body.orderId || !body.amount) {HttpServer.json(res, 400, { error: 'Missing required fields: orderId and amount.' });return;@@ -108,11 +115,20 @@ export function registerPaymentRoutes(server, ctx) {const isStale = (existing.status === PaymentStatus.ACTIVE && existing.expiresAt && existing.expiresAt.getTime() <= now) ||(existing.status === PaymentStatus.PROCESSING && existing.processingExpiresAt && existing.processingExpiresAt.getTime() <= now);if (isStale) {- ctx.sessionRepo.transitionToTerminal(existing.id, PaymentStatus.EXPIRED);+ const terminalStatus = existing.status === PaymentStatus.PROCESSING ? PaymentStatus.FAILED : PaymentStatus.EXPIRED;+ ctx.sessionRepo.transitionToTerminal(existing.id, terminalStatus);if (existing.receivingAccountId) {ctx.queueEngine.promoteNext(existing.receivingAccountId);}- existing.status = PaymentStatus.EXPIRED;+ existing.status = terminalStatus;+ if (ctx.eventEmitter) {+ ctx.eventEmitter.emit(`PAYMENT.${terminalStatus}`, {+ paymentId: existing.id,+ orderId: existing.orderId,+ merchantId: existing.merchantId,+ amountPaise: existing.amountPaise+ });+ }}// If existing is non-terminal (ACTIVE, PROCESSING, QUEUED, INITIATED):@@ -148,10 +164,9 @@ export function registerPaymentRoutes(server, ctx) {return;}- // CASE 4: Previous session is TERMINAL (FAILED, EXPIRED, CANCELLED) -> RETRY / NEW PAYMENT!- const cleanOrderId = body.orderId.replace(/-R\d+$/, '');- const randSuffix = Math.floor(1000 + Math.random() * 9000);- body.orderId = `${cleanOrderId}-R${randSuffix}`;+ // CASE 4: Previous session is TERMINAL (FAILED, EXPIRED, CANCELLED) -> RETRY / NEW ATTEMPT!+ // Invariant: Keep merchant's exact orderId untouched so webhooks, reconciliations, and reporting align.+ body.orderId = body.orderId.replace(/-R\d+$/, '');}let amountPaise;@@ -341,11 +356,12 @@ export function registerPaymentRoutes(server, ctx) {if (session.customerId && ctx.customerRepo) {const c = ctx.customerRepo.findById(session.customerId);if (c) {+ const isOwner = isPaymentOwner(req, session, ctx);customer = {id: c.id,name: c.name,- email: c.email,- mobileNumber: c.mobileNumber+ email: isOwner ? c.email : (c.email ? `${c.email.slice(0, 2)}***@${c.email.split('@')[1] || '***'}` : null),+ mobileNumber: isOwner ? c.mobileNumber : (c.mobileNumber ? `${c.mobileNumber.slice(0, 2)}******${c.mobileNumber.slice(-2)}` : null)};}}@@ -391,11 +407,12 @@ export function registerPaymentRoutes(server, ctx) {if (session.customerId && ctx.customerRepo) {const c = ctx.customerRepo.findById(session.customerId);if (c) {+ const isOwner = isPaymentOwner(req, session, ctx);customer = {id: c.id,name: c.name,- email: c.email,- mobileNumber: c.mobileNumber+ email: isOwner ? c.email : (c.email ? `${c.email.slice(0, 2)}***@${c.email.split('@')[1] || '***'}` : null),+ mobileNumber: isOwner ? c.mobileNumber : (c.mobileNumber ? `${c.mobileNumber.slice(0, 2)}******${c.mobileNumber.slice(-2)}` : null)};}}diff --git a/apps/payment-api/src/routes/pollers.routes.js b/apps/payment-api/src/routes/pollers.routes.jsindex 940496c..4df12f0 100644--- a/apps/payment-api/src/routes/pollers.routes.js+++ b/apps/payment-api/src/routes/pollers.routes.js@@ -4,7 +4,7 @@ import path from 'node:path';import { fileURLToPath } from 'node:url';import { HttpServer } from '../server.js';import { ObservationNormalizer, BankSmsParser, BankEmailParser, generateQrSvg } from '@youpi/core';-import { toRupeesString, toPaise, verifyHmac, resolveRuntimeUrls, resolveSecret, safeEqual, hasBearer, getObserverToken } from '@youpi/common';+import { toRupeesString, toPaise, verifyHmac, resolveRuntimeUrls, resolveSecret, safeEqual, hasBearer, getObserverToken, findUpiProviderByPackage } from '@youpi/common';import { isAdminRequest } from '../auth-guard.js';const __filename = fileURLToPath(import.meta.url);@@ -38,13 +38,14 @@ export function registerPollerRoutes(server, ctx) {HttpServer.json(res, 401, { error: 'Unauthorized', code: 'AUTH_REQUIRED' });return;}+ const sixtySecsAgo = new Date(Date.now() - 60000).toISOString();const activeSessions = ctx.db.query(`SELECT id, order_id, receiving_account_id, amount_paise, status, verification_level, expires_at, processing_expires_at, completed_atFROM payment_sessionsWHERE status IN ('ACTIVE', 'PROCESSING')- OR (status = 'SUCCESS' AND verification_level < 2 AND completed_at >= datetime('now', '-60 seconds'))+ OR (status = 'SUCCESS' AND verification_level < 2 AND completed_at >= ?)ORDER BY created_at DESC- `);+ `, [sixtySecsAgo]);const sessions = activeSessions.map(s => ({id: s.id,@@ -91,6 +92,7 @@ export function registerPollerRoutes(server, ctx) {sender,receivingAccountId: body.receivingAccountId,paymentSessionId: body.paymentSessionId,+ bankReferenceNumber: body.bankReferenceNumber || body.utr,// Test flags relax verification: honour them only for the admin credential, never for observers.isTest: Boolean(body.isTest) && isAdminRequest(req),testModeActive: Boolean(body.testModeActive) && isAdminRequest(req)@@ -117,6 +119,17 @@ export function registerPollerRoutes(server, ctx) {});return;}++ if (pipeResult.status === 'REJECTED') {+ HttpServer.json(res, 400, {+ accepted: false,+ status: 'REJECTED',+ reason: pipeResult.failingCondition,+ error: pipeResult.failingReason || pipeResult.details,+ pipeline: pipeResult+ });+ return;+ }}try {@@ -291,6 +304,35 @@ export function registerPollerRoutes(server, ctx) {let senderVpa = body.senderVpa;let observedAt = body.observedAt ? new Date(body.observedAt) : new Date();+ // Security Invariant (Issue #24): Validate Android notification package name if notification origin+ const notificationPackage = body.rawNotification?.package ? String(body.rawNotification.package).trim().toLowerCase() : null;+ if (notificationPackage) {+ const isKnownUpi = Boolean(findUpiProviderByPackage(notificationPackage));+ const KNOWN_NOTIFICATION_PACKAGES = new Set([+ 'com.google.android.apps.messaging',+ 'com.samsung.android.messaging',+ 'com.fampay.in',+ 'com.sbi.lotusintouch',+ 'com.snapwork.hdfc',+ 'com.csam.icici.bank.imobile',+ 'com.axis.mobile',+ 'com.msf.kbank.mobile',+ 'com.bankofbaroda.mconnect',+ 'com.idfcfirstbank.optimus',+ 'com.infrasofttech.indianbank',+ 'com.canarabank.mobility',+ 'com.infrasoft.uboi',+ 'com.fedmobile'+ ]);+ if (!isKnownUpi && !KNOWN_NOTIFICATION_PACKAGES.has(notificationPackage)) {+ HttpServer.json(res, 400, {+ accepted: false,+ error: `Untrusted Android notification package: ${notificationPackage}`+ });+ return;+ }+ }+// Check for raw SMS text inside body or rawNotificationconst rawText = body.body || body.sms || body.rawSms || body.message || body.text || body.rawNotification?.text;if (rawText && (!amountPaise || !bankRef)) {@@ -318,9 +360,10 @@ export function registerPollerRoutes(server, ctx) {const pipeResult = ctx.pipeline.process({source: 'SMS',rawText,- sender: body.sender || req.headers['x-sender'],+ sender: body.sender || req.headers['x-sender'] || body.rawNotification?.package,receivingAccountId,paymentSessionId: body.paymentSessionId,+ bankReferenceNumber: bankRef,isTest: false, // device-supplied flags must never relax verificationdeviceInfo: device ? `${device.device_name} (${device.device_model})` : 'Android SMS Gateway'});@@ -347,6 +390,18 @@ export function registerPollerRoutes(server, ctx) {});return;}++ if (pipeResult.status === 'REJECTED') {+ ctx.db.execute("UPDATE android_devices SET last_observation_at = datetime('now') WHERE id = ?", [deviceId]);+ HttpServer.json(res, 400, {+ accepted: false,+ status: 'REJECTED',+ reason: pipeResult.failingCondition,+ error: pipeResult.failingReason || pipeResult.details,+ pipeline: pipeResult+ });+ return;+ }}// Transport Only Contract (Part D): The Android observer forwards all raw SMS.diff --git a/packages/common/src/contracts.ts b/packages/common/src/contracts.tsindex 2d113ff..08d336c 100644--- a/packages/common/src/contracts.ts+++ b/packages/common/src/contracts.ts@@ -74,7 +74,7 @@ export interface WebhookEventPayload {// --- Observer Payload Contracts ---export interface AndroidObservationPayload {deviceId: string;- source: ObserverSource.ANDROID;+ source: ObserverSource.ANDROID_OBSERVER;amountPaise: number;observedAt: string;observationId?: string;diff --git a/packages/core/src/__tests__/webhook-engine.test.js b/packages/core/src/__tests__/webhook-engine.test.jsindex 9839346..c4b8c35 100644--- a/packages/core/src/__tests__/webhook-engine.test.js+++ b/packages/core/src/__tests__/webhook-engine.test.js@@ -99,10 +99,13 @@ describe('Webhook Engine Integration Tests', () => {assert.equal(hook.body.amount, '200.00');assert.equal(hook.body.amountPaise, 20000);- // Cryptographically verify signature using merchant webhookSecret+ // Cryptographically verify signature using merchant webhookSecret with timestamp bindingconst rawSig = hook.headers['x-gateway-signature'].replace('sha256=', '');- const isValid = verifyHmac(JSON.stringify(hook.body), merchant.webhookSecret, rawSig);+ const timestamp = hook.headers['x-gateway-timestamp'];+ assert.ok(timestamp);+ const isValid = verifyHmac(`${timestamp}.${JSON.stringify(hook.body)}`, merchant.webhookSecret, rawSig);assert.equal(isValid, true);+ assert.ok('utr' in hook.body);// Verify recorded in DB as successfulconst delivery = db.queryOne('SELECT * FROM webhook_deliveries WHERE id = ?', [result.deliveryId]);@@ -152,4 +155,34 @@ describe('Webhook Engine Integration Tests', () => {const updatedDelivery = db.queryOne('SELECT * FROM webhook_deliveries WHERE id = ?', [result.deliveryId]);assert.equal(updatedDelivery.is_successful, 1);});++ test('persists delivery failure record when merchant webhookSecret is missing', async () => {+ const merchantNoSecret = merchantRepo.create({+ businessName: 'No Secret Store',+ slug: 'no-secret-store',+ contactEmail: '[email protected]',+ contactPhone: '9876543210',+ webhookUrl: `http://localhost:${receiverPort}/webhook-no-secret`,+ webhookSecret: 'temp_secret'+ });+ // Explicitly set secret to empty string in DB to test missing secret guard+ db.execute("UPDATE merchants SET webhook_secret = '' WHERE id = ?", [merchantNoSecret.id]);++ const session = sessionRepo.create({+ merchantId: merchantNoSecret.id,+ orderId: 'HOOK-ORD-NO-SEC',+ amountPaise: 10000n+ });++ const res = await webhookEngine.dispatch('SUCCESS', session);+ assert.equal(res.delivered, false);+ assert.equal(res.status, 500);+ assert.ok(res.deliveryId);++ const recorded = db.queryOne('SELECT * FROM webhook_deliveries WHERE id = ?', [res.deliveryId]);+ assert.ok(recorded);+ assert.equal(recorded.is_successful, 0);+ assert.equal(recorded.response_status, 500);+ assert.match(recorded.response_body, /webhookSecret is not configured/);+ });});diff --git a/packages/core/src/bank-sms-parser.js b/packages/core/src/bank-sms-parser.jsindex ffed032..a8a49d7 100644--- a/packages/core/src/bank-sms-parser.js+++ b/packages/core/src/bank-sms-parser.js@@ -5,14 +5,30 @@ import { toPaise } from '@youpi/common';* Extracts amounts with prefix (Rs. 200, INR 500, ₹50), suffix (20.00 Rs),* proximity words ("20.00 received", "credited with 20.00"),* or standalone decimal amounts ("20.00").+ * Filters out available balance and credit limit clauses so balance amounts are never confused with payment amounts.* @param {string} text* @returns {{ amountStr: string, amountPaise: bigint } | null}*/export function extractIntelligentAmount(text) {if (!text || typeof text !== 'string') return null;- // Pattern 1: Standard currency prefix (e.g. Rs 499, Rs. 499, ₹499, INR 499, Rs. 20.00, ₹1,200.50)- const prefixMatch = text.match(/(?:(?:rs\.?|inr)\b|₹)[\s:=-]*([\d,]+(?:\.\d{1,2})?)/i);+ // 0. Remove balance mentions (e.g. "Avl Bal Rs 10,000", "Bal: INR 5000", "Available limit Rs. 20,000")+ // to avoid extracting account balance instead of credit amount.+ const balancePattern = /(?:(?:avl\b|avail\b|available\b|tot\b|total\b|ledger\b|clear\b|curr\b|current\b)\s*(?:bal\b|balance\b|limit\b)?|bal\b|balance\b)[\s:=-]*(?:(?:rs\b\.?|inr\b)|₹)?[\s:=-]*[\d,]+(?:\.\d{1,2})?/gi;+ const sanitizedText = text.replace(balancePattern, ' ').trim();++ // Pattern 0: Direct credit proximity phrases (e.g. "credited with Rs. 500", "received ₹200.00", "Rs 499.00 credited")+ const directCreditMatch = sanitizedText.match(/(?:credited\s*(?:with|by|for)?|received|deposit(?:ed)?)\s*[:=-]?\s*(?:(?:rs\b\.?|inr\b)|₹)?[\s:=-]*([\d,]+(?:\.\d{1,2})?)/i) ||+ sanitizedText.match(/(?:(?:rs\b\.?|inr\b)|₹)[\s:=-]*([\d,]+(?:\.\d{1,2})?)\s*(?:(?:has\s+been|is)\s+)?(?:credited|received|deposited)/i);+ if (directCreditMatch && (directCreditMatch[1] || directCreditMatch[2])) {+ const clean = (directCreditMatch[1] || directCreditMatch[2]).replace(/,/g, '');+ try {+ return { amountStr: clean, amountPaise: toPaise(clean) };+ } catch {}+ }++ // Pattern 1: Standard currency prefix on sanitized text (e.g. Rs 499, Rs. 499, ₹499, INR 499, Rs. 20.00, ₹1,200.50)+ const prefixMatch = sanitizedText.match(/(?:(?:rs\b\.?|inr\b)|₹)[\s:=-]*([\d,]+(?:\.\d{1,2})?)/i);if (prefixMatch && prefixMatch[1]) {const clean = prefixMatch[1].replace(/,/g, '');try {@@ -20,8 +36,8 @@ export function extractIntelligentAmount(text) {} catch {}}- // Pattern 2: Standard currency suffix (e.g. 499 Rs, 499.00 INR, 20.00 Rs, 20rs, 500 inr)- const suffixMatch = text.match(/(?:^|[^\w.])([\d,]+(?:\.\d{1,2})?)[\s:=-]*(?:(?:rs\.?|inr)\b|₹)/i);+ // Pattern 2: Standard currency suffix on sanitized text (e.g. 499 Rs, 499.00 INR, 20.00 Rs, 20rs, 500 inr)+ const suffixMatch = sanitizedText.match(/(?:^|[^\w.])([\d,]+(?:\.\d{1,2})?)[\s:=-]*(?:(?:rs\b\.?|inr\b)|₹)/i);if (suffixMatch && suffixMatch[1]) {const clean = suffixMatch[1].replace(/,/g, '');try {@@ -29,8 +45,8 @@ export function extractIntelligentAmount(text) {} catch {}}- // Pattern 3: Number adjacent to credit keywords (e.g. "20.00 received", "received 20.00", "credited 20", "20.00 credited")- const creditProximityMatch = text.match(/(?:credited|received|deposit|payment|paid|transferred|upi|cr)[\s\w:]*?([\d,]+(?:\.\d{1,2})?)|([\d,]+(?:\.\d{1,2})?)[\s\w:]*?(?:credited|received|deposit|payment|paid|transferred|upi|cr)/i);+ // Pattern 3: Number adjacent to credit keywords+ const creditProximityMatch = sanitizedText.match(/(?:credited|received|deposit|cr)[\s\w:]*?([\d,]+(?:\.\d{1,2})?)|([\d,]+(?:\.\d{1,2})?)[\s\w:]*?(?:credited|received|deposit|cr)/i);if (creditProximityMatch) {const rawVal = creditProximityMatch[1] || creditProximityMatch[2];if (rawVal) {@@ -44,7 +60,7 @@ export function extractIntelligentAmount(text) {}// Pattern 4: Standalone decimal currency number (e.g. 20.00, 150.50, 449.00)- const standaloneDecimal = text.match(/\b(\d{1,6}\.\d{2})\b/);+ const standaloneDecimal = sanitizedText.match(/\b(\d{1,6}\.\d{2})\b/);if (standaloneDecimal && standaloneDecimal[1]) {const clean = standaloneDecimal[1];try {@@ -84,15 +100,24 @@ export class BankSmsParser {const text = (sms.text || '').trim().slice(0, MAX_SCAN_CHARS);if (!text) return null;- // Check if SMS represents an incoming credit- const creditKeywords = /(credited|received|deposit|payment received|payment|upi\/cr|transferred)/i;+ // Check if SMS represents an incoming credit. Bare "payment" or "transferred" without credit context is rejected.+ const creditKeywords = /\b(credited|received|deposit|deposited|payment received|money received|added to (?:your )?(?:account|wallet)|upi\/cr)\b/i;if (!creditKeywords.test(text)) {return null;}- // Ignore pure debits- if (/(debited|withdrawn|sent rs|paid rs)/i.test(text) && !/(credited|received|deposit)/i.test(text)) {- return null;+ // Reject debit notifications:+ // If debit indicators exist and appear before credit indicators (e.g. "debited ... credited back in 48h")+ // or if the account itself is being debited, reject immediately.+ const debitIdx = text.search(/\b(?:debited|withdrawn|deducted|spent|paid rs|sent rs)\b/i);+ const creditIdx = text.search(/\b(?:credited|received|deposit|deposited)\b/i);+ if (debitIdx !== -1) {+ if (creditIdx === -1 || debitIdx < creditIdx) {+ return null;+ }+ if (/\b(?:debited\s*(?:from|by|for)|is\s+debited|has\s+been\s+debited)\b/i.test(text)) {+ return null;+ }}// 1. Extract Amount using Intelligent Multi-Pattern Extractor@@ -101,11 +126,12 @@ export class BankSmsParser {return null;}- // 2. Extract Bank Reference / UTR / RRN+ // 2. Extract Bank Reference / UTR / RRN (including FamPay Transaction IDs)let bankRef;const utrPatterns = [- /(?:upi\s*ref(?:erence)?\s*(?:no\.?|num)?|utr(?:\s*no\.?)?|rrn(?:\s*no\.?)?|txn\s*(?:id|ref)?|ref\s*no\.?)[\s:=-]+([a-zA-Z0-9]{6,25})/i,- /(?:ref\s*no\.?)?[\s:#=-]+([a-zA-Z0-9]{8,22})/i,+ /(?:upi\s*ref(?:erence)?\s*(?:no\.?|num)?|utr(?:\s*no\.?)?|rrn(?:\s*no\.?)?|txn\s*(?:id|ref|#)?|transaction\s*id|ref\s*no\.?)[\s:=-]+([a-zA-Z0-9\-_]{6,35})/i,+ /(?:upi\/(?:[0-9]+\/|cr\/)([a-zA-Z0-9\-_]{6,35}))/i,+ /\b(?:ref(?:\s*(?:no\.?|id|#))?)[:\s#=-]+([a-zA-Z0-9\-_]{6,35})/i,/\b([0-9]{12})\b/];@@ -117,9 +143,9 @@ export class BankSmsParser {}}- // 3. Extract Sender VPA+ // 3. Extract Sender VPA (including FamPay formats like "from Rahul (UPI ID: rahul@fam)")let senderVpa;- const vpaMatch = text.match(/(?:from|by|vpa)\s+([a-zA-Z0-9.\-_]{2,64}@[a-zA-Z0-9.\-_]{2,32})/i);+ const vpaMatch = text.match(/(?:from|by|vpa|upi\s*id)[\s:]+(?:[a-zA-Z\s]+[\(\[])?([a-zA-Z0-9.\-_]{2,64}@[a-zA-Z0-9.\-_]{2,32})/i);if (vpaMatch && vpaMatch[1]) {senderVpa = vpaMatch[1].trim().replace(/[.,;]+$/, '');}diff --git a/packages/core/src/verification-pipeline.js b/packages/core/src/verification-pipeline.jsindex f195382..c97f198 100644--- a/packages/core/src/verification-pipeline.js+++ b/packages/core/src/verification-pipeline.js@@ -123,7 +123,7 @@ export class PaymentVerificationPipeline {// Bank credit notifications are a few hundred bytes. Capping the text bounds the cost of// the reference-extraction regexes below, which are scanned from every start offset and// would otherwise let one oversized "observation" block the event loop (ReDoS / DoS).- const MAX_SCAN_CHARS = 16384;+ const MAX_SCAN_CHARS = 8192;const rawText = (input.rawText || '').toString().slice(0, MAX_SCAN_CHARS);// =========================================================================@@ -187,7 +187,8 @@ export class PaymentVerificationPipeline {stage5,stage6,parsed,- session+ session,+ attribution = null}) => {return {success: finalStatus === 'VERIFIED',@@ -218,10 +219,21 @@ export class PaymentVerificationPipeline {orderId: session.orderId,amountPaise: session.amountPaise?.toString(),status: session.status- } : null+ } : null,+ attribution: attribution || null};};+ // Invariant Guard: Bounded rawText boundary to prevent ReDoS (CWE-400)+ if (input.rawText && typeof input.rawText === 'string' && input.rawText.length > MAX_SCAN_CHARS) {+ return buildResult({+ finalStatus: 'REJECTED',+ failingStage: 1,+ failingCondition: 'PAYLOAD_TOO_LARGE',+ failingReason: `Transaction notification payload exceeds maximum allowable length of ${MAX_SCAN_CHARS} characters (received ${input.rawText.length}).`+ });+ }+// 0. Resolve Payment Session and Customer Context early for security attributionlet session = null;@@ -366,10 +378,31 @@ export class PaymentVerificationPipeline {emailDomain = cleanEmail.toLowerCase().trim().replace(/[>]/g, '');}- // Universal Bank Identifier: Email domain ends with .bank.in (e.g. [email protected], [email protected])- const isBankDomain = emailDomain.endsWith('.bank.in') || emailDomain === 'bank.in';+ // Universal Bank Identifier: Email domain ends with .bank.in/.fin.in or is an official verified Indian bank domain+ const KNOWN_BANK_DOMAINS = new Set([+ 'hdfcbank.net', 'hdfcbank.com',+ 'icicibank.com',+ 'sbi.co.in',+ 'axisbank.com',+ 'kotak.com', 'kotak.co.in',+ 'paytmbank.com', 'paytm.com',+ 'yesbank.in', 'pnb.co.in',+ 'bankofbaroda.co.in', 'bankofbaroda.com',+ 'indusind.com',+ 'idfcfirstbank.com', 'idfcbank.com',+ 'canarabank.com',+ 'unionbankofindia.co.in',+ 'federalbank.co.in',+ 'idbibank.com'+ ]);+ const isBankDomain =+ emailDomain.endsWith('.bank.in') ||+ emailDomain.endsWith('.fin.in') ||+ emailDomain === 'bank.in' ||+ emailDomain === 'fin.in' ||+ Array.from(KNOWN_BANK_DOMAINS).some(root => emailDomain === root || emailDomain.endsWith('.' + root));// In automated test suite or local dev, allow TEST sender and legacy test fixture domains- const isValidDomain = isBankDomain || sender === 'TEST' || cleanEmail === 'TEST' || sender === 'gmail-browser-automator' || emailDomain.endsWith('.youpi.local') || emailDomain === 'hdfcbank.net';+ const isValidDomain = isBankDomain || sender === 'TEST' || cleanEmail === 'TEST' || sender === 'gmail-browser-automator' || emailDomain.endsWith('.youpi.local');if (!isValidDomain) {if (!isAttributableToCustomer) {@@ -471,17 +504,27 @@ export class PaymentVerificationPipeline {}// Invariant 3: Check 12-digit reference (UTR / RRN)- let bankRef = null;- const ref12Patterns = [- /(?:upi\s*ref(?:erence)?\s*(?:no\.?|num)?|utr(?:\s*no\.?)?|rrn(?:\s*no\.?)?|txn\s*(?:id|ref)?|ref\s*no\.?)[\s:=-]+([0-9]{12})\b/i,- /(?:ref\s*no\.?)?[\s:#=-]+([0-9]{12})\b/i,- /\b([0-9]{12})\b/- ];- for (const pat of ref12Patterns) {- const match = rawText.match(pat);- if (match && match[1]) {- bankRef = match[1].trim();- break;+ let bankRef = input.bankReferenceNumber || input.utr || null;+ if (!bankRef) {+ const ref12Patterns = [+ /(?:upi\s*ref(?:erence)?\s*(?:no\.?|num)?|utr(?:\s*no\.?)?|rrn(?:\s*no\.?)?|txn\s*(?:id|ref)?|ref\s*no\.?)[\s:=-]+([0-9]{12})\b/i,+ /(?:ref\s*no\.?)?[\s:#=-]+([0-9]{12})\b/i,+ /\b([0-9]{12})\b/+ ];+ for (const pat of ref12Patterns) {+ const match = rawText.match(pat);+ if (match && match[1]) {+ bankRef = match[1].trim();+ break;+ }+ }+ }++ if (!bankRef && isGmailSource) {+ const generalRefMatch = rawText.match(/(?:utr|ref(?:\s*no\.?)?|txn\s*(?:id|ref)?|rrn)[:\s#]+([a-zA-Z0-9\-_]{6,35})/i) ||+ rawText.match(/UPI\/CR\/([a-zA-Z0-9\-_]+)/i);+ if (generalRefMatch && generalRefMatch[1]) {+ bankRef = generalRefMatch[1].trim();}}@@ -633,15 +676,18 @@ export class PaymentVerificationPipeline {});}- if (session.expiresAt) {- const sessionExpiresAt = parseSessionTime(session.expiresAt);- if (receivedAt.getTime() > sessionExpiresAt.getTime()) {+ const activeDeadline = (session.status === PaymentStatus.PROCESSING && (session.processingExpiresAt || session.processing_expires_at))+ ? parseSessionTime(session.processingExpiresAt || session.processing_expires_at)+ : (session.expiresAt || session.expires_at ? parseSessionTime(session.expiresAt || session.expires_at) : null);++ if (activeDeadline) {+ if (receivedAt.getTime() > activeDeadline.getTime()) {stage4 = {stage: 4,name: 'VERIFICATION',status: 'FAILED',reason: 'SESSION_EXPIRED',- details: `Observation received timestamp (${receivedAt.toISOString()}) is after payment session expiration (${sessionExpiresAt.toISOString()}).`+ details: `Observation received timestamp (${receivedAt.toISOString()}) is after payment session expiration (${activeDeadline.toISOString()}).`};return buildResult({finalStatus: 'REJECTED',@@ -1073,8 +1119,11 @@ export class PaymentVerificationPipeline {status: attributionResult.attributed ? 'ATTRIBUTED' : 'UNRESOLVED',outcomeStatus: attributionResult.outcomeStatus,details: {+ attributed: attributionResult.attributed,+ paymentSessionId: attributionResult.paymentSessionId,observationId: attributionResult.observationId,attributedSessionId: attributionResult.paymentSessionId,+ outcomeStatus: attributionResult.outcomeStatus,verificationLevel: attributionResult.verificationLevel,verificationTag: attributionResult.verificationTag}@@ -1093,7 +1142,8 @@ export class PaymentVerificationPipeline {stage5,stage6,parsed: parsedData,- session: updatedSession || session+ session: updatedSession || session,+ attribution: attributionResult});}}diff --git a/packages/core/src/webhook-engine.js b/packages/core/src/webhook-engine.jsindex 22c4acd..a75b2fd 100644--- a/packages/core/src/webhook-engine.js+++ b/packages/core/src/webhook-engine.js@@ -28,23 +28,72 @@ 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;+ 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;+ }+ } catch {}+ }const payloadObj = {event: publicOutcome,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,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(),@@ -52,9 +101,10 @@ export class WebhookEngine {};const payloadString = JSON.stringify(payloadObj);- const signature = generateHmac(payloadString, merchant.webhookSecret);- const deliveryId = crypto.randomUUID();const timestamp = Date.now().toString();+ // Invariant: Sign `${timestamp}.${payloadString}` to bind timestamp into HMAC for replay protection+ const signature = generateHmac(`${timestamp}.${payloadString}`, merchant.webhookSecret);+ const deliveryId = crypto.randomUUID();const headers = {'Content-Type': 'application/json',@@ -73,7 +123,7 @@ export class WebhookEngine {method: 'POST',headers,body: payloadString,- // Never follow redirects: a public URL could otherwise 302 into the internal network.+ // Never follow redirects: a public URL could otherwise 302 into internal network (SSRF)redirect: 'manual',signal: AbortSignal.timeout(10000) // 10s timeout});@@ -86,7 +136,6 @@ export class WebhookEngine {}// Persist delivery record in webhook_deliveries- const nowIso = new Date().toISOString();const nextRetryAt = isSuccessful? null: new Date(Date.now() + 5000).toISOString(); // initial 5s backoff@@ -119,30 +168,65 @@ export class WebhookEngine {}/**- * Retries overdue pending webhook deliveries with exponential backoff.+ * Retries overdue pending webhook deliveries with atomic claim & exponential backoff.* Backoff strategy: 5s, 30s, 2m, 10m, 1h*/async retryPending() {const nowIso = new Date().toISOString();- const pending = this.db.query(`- SELECT * FROM webhook_deliveries- WHERE is_successful = 0 AND attempt_count < ? AND next_retry_at <= ?- LIMIT 20- `, [this.maxRetries, nowIso]);++ // Invariant: Atomically claim overdue pending deliveries in a transaction to prevent duplicate dispatches+ const claimed = this.db.transaction(() => {+ const pending = this.db.query(`+ SELECT id, merchant_id, payment_id, event_type, payload, endpoint_url, attempt_count+ FROM webhook_deliveries+ WHERE is_successful = 0 AND attempt_count < ? AND next_retry_at <= ?+ LIMIT 20+ `, [this.maxRetries, nowIso]);++ if (pending.length === 0) return [];++ // Lock claimed items by setting next_retry_at 60 seconds into the future+ const claimLockIso = new Date(Date.now() + 60000).toISOString();+ for (const item of pending) {+ this.db.execute(`+ UPDATE webhook_deliveries+ SET next_retry_at = ?, attempt_count = attempt_count + 1+ WHERE id = ?+ `, [claimLockIso, item.id]);+ }++ return pending;+ });++ if (claimed.length === 0) return [];const results = [];const backoffs = [5000, 30000, 120000, 600000, 3600000];- for (const item of pending) {+ for (const item of claimed) {const merchant = this.merchantRepo.findById(item.merchant_id);- if (!merchant || !item.endpoint_url) continue;+ if (!merchant || !merchant.webhookSecret || !item.endpoint_url) {+ this.db.execute(`+ UPDATE webhook_deliveries+ SET is_successful = 0, next_retry_at = NULL, response_body = 'Missing merchant or webhookSecret'+ WHERE id = ?+ `, [item.id]);+ continue;+ }// Re-validate the stored endpoint before every retry (SSRF guard).const retryEndpoint = validateOutboundWebhookUrl(item.endpoint_url);- if (!retryEndpoint.valid) continue;+ if (!retryEndpoint.valid) {+ this.db.execute(`+ UPDATE webhook_deliveries+ SET is_successful = 0, next_retry_at = NULL, response_body = ?+ WHERE id = ?+ `, [`SSRF blocked: ${retryEndpoint.error}`, item.id]);+ continue;+ }- const signature = generateHmac(item.payload, merchant.webhookSecret);const timestamp = Date.now().toString();+ const signature = generateHmac(`${timestamp}.${item.payload}`, merchant.webhookSecret);let isSuccess = false;let respStatus = null;@@ -169,7 +253,7 @@ export class WebhookEngine {respBody = err.message;}- const nextAttempt = item.attempt_count + 1;+ const nextAttempt = item.attempt_count + 1; // item.attempt_count was already incremented during claimconst nextRetryDelay = backoffs[Math.min(nextAttempt - 1, backoffs.length - 1)];const nextRetryAt = isSuccess || nextAttempt >= this.maxRetries? null@@ -177,10 +261,9 @@ export class WebhookEngine {this.db.execute(`UPDATE webhook_deliveries- SET attempt_count = ?, is_successful = ?, response_status = ?,- response_body = ?, next_retry_at = ?+ SET is_successful = ?, response_status = ?, response_body = ?, next_retry_at = ?WHERE id = ?- `, [nextAttempt, isSuccess ? 1 : 0, respStatus, respBody, nextRetryAt, item.id]);+ `, [isSuccess ? 1 : 0, respStatus, respBody, nextRetryAt, item.id]);results.push({ id: item.id, success: isSuccess, attempt: nextAttempt });}diff --git a/packages/db/src/repositories/customer.repository.js b/packages/db/src/repositories/customer.repository.jsindex 5e3a90e..aa5ac67 100644--- a/packages/db/src/repositories/customer.repository.js+++ b/packages/db/src/repositories/customer.repository.js@@ -115,8 +115,8 @@ export class CustomerRepository {if (!normalized) return null;const clean10 = normalized.slice(-10);const row = this.db.queryOne(- 'SELECT * FROM customers WHERE mobile_number = ? OR mobile_number = ? OR mobile_number = ? OR mobile_number LIKE ?',- [normalized, clean10, '+91' + clean10, '%' + clean10]+ 'SELECT * FROM customers WHERE mobile_number IN (?, ?, ?)',+ [normalized, clean10, '+91' + clean10]);if (!row) return null;return this.mapRow(row);@@ -279,32 +279,35 @@ export class CustomerRepository {if (!id) return null;const now = new Date().toISOString();const lastDevice = options.lastDevice || options.deviceInfo || null;- this.db.execute(- "UPDATE customers SET status = 'BANNED', ban_reason = ?, banned_at = ?, last_device = COALESCE(?, last_device), updated_at = ? WHERE id = ?",- [reason, now, lastDevice, now, id]- );- // Immediately transition all existing non-terminal sessions for this customer to EXPIRED (Section 10, Test 18)- const activeSessions = this.db.query(- "SELECT id, receiving_account_id FROM payment_sessions WHERE customer_id = ? AND status IN ('INITIATED', 'QUEUED', 'ACTIVE', 'PROCESSING')",- [id]- );- if (activeSessions.length > 0) {+ return this.db.transaction(() => {this.db.execute(- "UPDATE payment_sessions SET status = 'EXPIRED', updated_at = ? WHERE customer_id = ? AND status IN ('INITIATED', 'QUEUED', 'ACTIVE', 'PROCESSING')",- [now, id]+ "UPDATE customers SET status = 'BANNED', ban_reason = ?, banned_at = ?, last_device = COALESCE(?, last_device), updated_at = ? WHERE id = ?",+ [reason, now, lastDevice, now, id]);- for (const s of activeSessions) {- if (s.receiving_account_id) {- this.db.execute(- "UPDATE payment_receiving_accounts SET is_slot_busy = 0, current_active_session_id = NULL WHERE id = ? AND current_active_session_id = ?",- [s.receiving_account_id, s.id]- );++ // Immediately transition all existing non-terminal sessions for this customer to EXPIRED (Section 10, Test 18)+ const activeSessions = this.db.query(+ "SELECT id, receiving_account_id FROM payment_sessions WHERE customer_id = ? AND status IN ('INITIATED', 'QUEUED', 'ACTIVE', 'PROCESSING')",+ [id]+ );+ if (activeSessions.length > 0) {+ this.db.execute(+ "UPDATE payment_sessions SET status = 'EXPIRED', updated_at = ? WHERE customer_id = ? AND status IN ('INITIATED', 'QUEUED', 'ACTIVE', 'PROCESSING')",+ [now, id]+ );+ for (const s of activeSessions) {+ if (s.receiving_account_id) {+ this.db.execute(+ "UPDATE payment_receiving_accounts SET is_slot_busy = 0, current_active_session_id = NULL WHERE id = ? AND current_active_session_id = ?",+ [s.receiving_account_id, s.id]+ );+ }}}- }- return this.findById(id);+ return this.findById(id);+ });}/**diff --git a/packages/db/src/repositories/payment-session.repository.js b/packages/db/src/repositories/payment-session.repository.jsindex ea8d10c..17683f8 100644--- a/packages/db/src/repositories/payment-session.repository.js+++ b/packages/db/src/repositories/payment-session.repository.js@@ -13,14 +13,15 @@ export class PaymentSessionRepository {const id = data.id || crypto.randomUUID();const now = new Date().toISOString();const metadata = typeof data.metadata === 'object' ? JSON.stringify(data.metadata) : (data.metadata || '{}');+ const attemptId = data.attemptId || id;const sql = `INSERT INTO payment_sessions (- id, merchant_id, customer_id, receiving_account_id, order_id,+ id, merchant_id, customer_id, receiving_account_id, order_id, attempt_id,amount_paise, currency, method, status, queue_position,return_url, idempotency_key, device_id, verification_level, verification_sources,verification_tag, metadata, created_at, updated_at- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, '[]', 'UNVERIFIED', ?, ?, ?)+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, '[]', 'UNVERIFIED', ?, ?, ?)`;this.db.execute(sql, [@@ -29,6 +30,7 @@ export class PaymentSessionRepository {data.customerId || null,data.receivingAccountId || null,data.orderId,+ attemptId,Number(data.amountPaise),data.currency || 'INR',data.method || PaymentMethod.UPI,@@ -53,7 +55,7 @@ export class PaymentSessionRepository {findByOrderId(merchantId, orderId) {const row = this.db.queryOne(- 'SELECT * FROM payment_sessions WHERE merchant_id = ? AND order_id = ?',+ 'SELECT * FROM payment_sessions WHERE merchant_id = ? AND order_id = ? ORDER BY created_at DESC LIMIT 1',[merchantId, orderId]);if (!row) return null;@@ -459,11 +461,11 @@ export class PaymentSessionRepository {const rows = this.db.query(`SELECT * FROM payment_sessionsWHERE receiving_account_id = ?- AND status IN (?, ?)+ AND status IN (?, ?, ?)AND updated_at >= ?ORDER BY updated_at DESCLIMIT 20- `, [receivingAccountId, PaymentStatus.EXPIRED, PaymentStatus.FAILED, sinceDate.toISOString()]);+ `, [receivingAccountId, PaymentStatus.EXPIRED, PaymentStatus.FAILED, PaymentStatus.CANCELLED, sinceDate.toISOString()]);return rows.map(r => this.mapRow(r));}@@ -586,6 +588,7 @@ export class PaymentSessionRepository {customerId: row.customer_id,receivingAccountId: row.receiving_account_id,orderId: row.order_id,+ attemptId: row.attempt_id || row.id,amountPaise: BigInt(row.amount_paise),currency: row.currency,method: row.method,diff --git a/packages/db/src/sqlite-schema.sql b/packages/db/src/sqlite-schema.sqlindex 0243ce2..95220e8 100644--- a/packages/db/src/sqlite-schema.sql+++ b/packages/db/src/sqlite-schema.sql@@ -43,6 +43,10 @@ CREATE TABLE IF NOT EXISTS customers (otp_attempts INTEGER NOT NULL DEFAULT 0,is_phone_verified INTEGER DEFAULT 0,status TEXT NOT NULL DEFAULT 'ACTIVE',+ ban_reason TEXT,+ banned_at TEXT,+ unbanned_at TEXT,+ last_device TEXT,last_login_at TEXT,created_at TEXT NOT NULL DEFAULT (datetime('now')),updated_at TEXT NOT NULL DEFAULT (datetime('now'))@@ -67,6 +71,28 @@ CREATE TABLE IF NOT EXISTS customer_sessions (CREATE INDEX IF NOT EXISTS idx_customer_sessions_token ON customer_sessions (token, is_active);CREATE INDEX IF NOT EXISTS idx_customer_sessions_customer ON customer_sessions (customer_id);+-- 3c. Devices Table (Cryptographic Device Binding & Hardware Context Fingerprinting)+CREATE TABLE IF NOT EXISTS devices (+ id TEXT PRIMARY KEY,+ customer_id TEXT REFERENCES customers(id) ON DELETE SET NULL,+ public_key TEXT NOT NULL,+ fingerprint_hash TEXT NOT NULL,+ user_agent TEXT,+ platform TEXT,+ browser TEXT,+ timezone TEXT,+ language TEXT,+ screen_signature TEXT,+ device_token TEXT UNIQUE,+ status TEXT NOT NULL DEFAULT 'ACTIVE',+ created_at TEXT NOT NULL DEFAULT (datetime('now')),+ last_seen_at TEXT NOT NULL DEFAULT (datetime('now'))+);++CREATE INDEX IF NOT EXISTS idx_devices_customer ON devices (customer_id);+CREATE INDEX IF NOT EXISTS idx_devices_fingerprint ON devices (fingerprint_hash);+CREATE INDEX IF NOT EXISTS idx_devices_token ON devices (device_token);+-- 4. Payment Sessions TableCREATE TABLE IF NOT EXISTS payment_sessions (id TEXT PRIMARY KEY,@@ -74,6 +100,7 @@ CREATE TABLE IF NOT EXISTS payment_sessions (customer_id TEXT REFERENCES customers(id) ON DELETE SET NULL,receiving_account_id TEXT REFERENCES payment_receiving_accounts(id),order_id TEXT NOT NULL,+ attempt_id TEXT,amount_paise INTEGER NOT NULL CHECK (amount_paise > 0),currency TEXT NOT NULL DEFAULT 'INR',method TEXT NOT NULL DEFAULT 'UPI',@@ -93,11 +120,17 @@ CREATE TABLE IF NOT EXISTS payment_sessions (verification_tag TEXT DEFAULT 'UNVERIFIED',metadata TEXT NOT NULL DEFAULT '{}',created_at TEXT NOT NULL DEFAULT (datetime('now')),- updated_at TEXT NOT NULL DEFAULT (datetime('now')),- UNIQUE(merchant_id, order_id)+ updated_at TEXT NOT NULL DEFAULT (datetime('now')));CREATE INDEX IF NOT EXISTS idx_payment_sessions_active ON payment_sessions (receiving_account_id, status);+CREATE INDEX IF NOT EXISTS idx_payment_sessions_order ON payment_sessions (merchant_id, order_id, created_at);+CREATE INDEX IF NOT EXISTS idx_payment_sessions_device ON payment_sessions (device_id);+-- At most one active/processing/queued/successful session per merchant order.+-- Retrying a terminal (FAILED, EXPIRED, CANCELLED) order allows a new attempt with the true orderId.+CREATE UNIQUE INDEX IF NOT EXISTS idx_single_active_session_per_order+ ON payment_sessions (merchant_id, order_id)+ WHERE status NOT IN ('FAILED', 'EXPIRED', 'CANCELLED');-- Slot exclusivity is a database invariant, not an application convention: at most one-- session per receiving account may occupy the slot (ACTIVE or PROCESSING) at any time.-- Concurrent writers are rejected by the engine instead of relying on lock contention.@@ -123,6 +156,9 @@ CREATE TABLE IF NOT EXISTS payment_observations ();CREATE INDEX IF NOT EXISTS idx_observations_match ON payment_observations (receiving_account_id, amount_paise, attribution_status);+CREATE INDEX IF NOT EXISTS idx_observations_bank_ref ON payment_observations (bank_reference_number);+CREATE INDEX IF NOT EXISTS idx_observations_fingerprint ON payment_observations (fingerprint_hash);+CREATE INDEX IF NOT EXISTS idx_observations_attributed_payment ON payment_observations (attributed_payment_id);-- 6. Android Devices TableCREATE TABLE IF NOT EXISTS android_devices (@@ -153,6 +189,8 @@ CREATE TABLE IF NOT EXISTS webhook_deliveries (created_at TEXT NOT NULL DEFAULT (datetime('now')));+CREATE INDEX IF NOT EXISTS idx_webhook_deliveries_retry ON webhook_deliveries (is_successful, next_retry_at);+-- 8. Support Tickets & Ticket MessagesCREATE TABLE IF NOT EXISTS support_tickets (id TEXT PRIMARY KEY,@@ -165,6 +203,9 @@ CREATE TABLE IF NOT EXISTS support_tickets (updated_at TEXT NOT NULL DEFAULT (datetime('now')));+CREATE INDEX IF NOT EXISTS idx_support_tickets_merchant ON support_tickets (merchant_id);+CREATE INDEX IF NOT EXISTS idx_support_tickets_customer ON support_tickets (customer_id);+CREATE TABLE IF NOT EXISTS ticket_messages (id TEXT PRIMARY KEY,ticket_id TEXT NOT NULL REFERENCES support_tickets(id) ON DELETE CASCADE,@@ -175,6 +216,8 @@ CREATE TABLE IF NOT EXISTS ticket_messages (created_at TEXT NOT NULL DEFAULT (datetime('now')));+CREATE INDEX IF NOT EXISTS idx_ticket_messages_ticket ON ticket_messages (ticket_id);+-- 9. Audit Logs TableCREATE TABLE IF NOT EXISTS audit_logs (id TEXT PRIMARY KEY,@@ -189,6 +232,9 @@ CREATE TABLE IF NOT EXISTS audit_logs (created_at TEXT NOT NULL DEFAULT (datetime('now')));+CREATE INDEX IF NOT EXISTS idx_audit_logs_merchant ON audit_logs (merchant_id);+CREATE INDEX IF NOT EXISTS idx_audit_logs_entity ON audit_logs (entity_type, entity_id);+-- 10. Security Events Table (Forensic evidence for fraud, automatic and manual bans)CREATE TABLE IF NOT EXISTS security_events (id TEXT PRIMARY KEY,@@ -214,27 +260,5 @@ CREATE INDEX IF NOT EXISTS idx_security_events_customer ON security_events (custCREATE INDEX IF NOT EXISTS idx_security_events_session ON security_events (payment_session_id);CREATE INDEX IF NOT EXISTS idx_security_events_type ON security_events (event_type);--- 11. Devices Table (Cryptographic Device Binding & Hardware Context Fingerprinting)-CREATE TABLE IF NOT EXISTS devices (- id TEXT PRIMARY KEY,- customer_id TEXT REFERENCES customers(id) ON DELETE SET NULL,- public_key TEXT NOT NULL,- fingerprint_hash TEXT NOT NULL,- user_agent TEXT,- platform TEXT,- browser TEXT,- timezone TEXT,- language TEXT,- screen_signature TEXT,- device_token TEXT UNIQUE,- status TEXT NOT NULL DEFAULT 'ACTIVE',- created_at TEXT NOT NULL DEFAULT (datetime('now')),- last_seen_at TEXT NOT NULL DEFAULT (datetime('now'))-);--CREATE INDEX IF NOT EXISTS idx_devices_customer ON devices (customer_id);-CREATE INDEX IF NOT EXISTS idx_devices_fingerprint ON devices (fingerprint_hash);-CREATE INDEX IF NOT EXISTS idx_devices_token ON devices (device_token);-CREATE INDEX IF NOT EXISTS idx_payment_sessions_device ON payment_sessions (device_id);diff --git a/packages/observer-sdk/src/client.js b/packages/observer-sdk/src/client.jsindex 3c2390e..ce0b14e 100644--- a/packages/observer-sdk/src/client.js+++ b/packages/observer-sdk/src/client.js@@ -54,6 +54,25 @@ export class PaymentObserverClient {return await res.json();}+ /**+ * Fetches active window sessions from payment core with observer bearer authentication.+ * @returns {Promise<Array<any>>}+ */+ async getActiveWindow() {+ const url = `${this.apiBaseUrl}/api/v1/pollers/active-window`;+ try {+ const res = await fetch(url, {+ headers: { 'Authorization': `Bearer ${getObserverToken()}` },+ signal: AbortSignal.timeout(3000)+ });+ if (res.ok) {+ const data = await res.json();+ return data.sessions || [];+ }+ } catch {}+ return [];+ }+/*** Submits signed observation from Android Observer with HMAC-SHA256 signature.* @param {{diff --git a/scripts/execute-clean-customer-reset.js b/scripts/execute-clean-customer-reset.jsindex ab8f447..92daea4 100644--- a/scripts/execute-clean-customer-reset.js+++ b/scripts/execute-clean-customer-reset.js@@ -8,6 +8,13 @@ async function executeCleanReset() {console.log('🛡️ EXECUTING ZERO-CUSTOMER CLEAN RESET ON DEV AND PROD');console.log('============================================================');+ const isConfirmed = process.argv.includes('--confirm-clean-customer-reset') || process.env.ALLOW_CUSTOMER_RESET === 'true';+ if (!isConfirmed) {+ console.error('\n❌ [SAFETY ABORT] Clean customer database reset requires explicit confirmation.');+ console.error('To proceed, re-run with `--confirm-clean-customer-reset` or set `ALLOW_CUSTOMER_RESET=true`.\n');+ process.exit(1);+ }+// --- 1. PRODUCTION RESET ---const prodPath = path.resolve('data/youpi_pg.sqlite');console.log('\n[1] Processing Production Database:', prodPath);@@ -17,10 +24,17 @@ async function executeCleanReset() {fs.mkdirSync(prodBackupDir, { recursive: true });}const prodBackupPath = path.join(prodBackupDir, `prod_pre_auth_reset_${Date.now()}.sqlite`);- fs.copyFileSync(prodPath, prodBackupPath);- console.log(' [✓] Created production backup at:', prodBackupPath);-const prodDb = new Database({ dbPath: prodPath });++ try {+ prodDb.execute('VACUUM INTO ?', [prodBackupPath]);+ console.log(' [✓] Created WAL-consistent atomic production backup at:', prodBackupPath);+ } catch (err) {+ console.warn(' [!] VACUUM INTO failed, falling back to copyFileSync:', err.message);+ if (fs.existsSync(prodPath)) {+ fs.copyFileSync(prodPath, prodBackupPath);+ }+ }const prodMerchantsBefore = prodDb.query('SELECT count(*) as c FROM merchants')[0].c;const prodAccountsBefore = prodDb.query('SELECT count(*) as c FROM payment_receiving_accounts')[0].c;diff --git a/scripts/test-support.js b/scripts/test-support.jsindex d902883..ec7462b 100644--- a/scripts/test-support.js+++ b/scripts/test-support.js@@ -22,7 +22,7 @@ export function authFetch(url, init = {}) {return fetch(url, { ...init, headers: { ...authHeadersFor(url), ...(init.headers || {}) } });}-const GUARDED = /\/api\/v1\/admin\/|\/api\/v1\/pollers\/events|\/api\/v1\/pollers\/active-window|\/simulate-observation/;+const GUARDED = /\/api\/v1\/admin\/|\/api\/v1\/pollers\/events|\/api\/v1\/pollers\/active-window|\/simulate-observation|\/api\/v1\/orders\/[^\/]+\/cod|\/api\/v1\/payments\/[^\/]+\/cod/;/** Admin bearer header only for routes the gateway guards; other routes (customer auth etc.) get none. */export function authHeadersFor(path, extra = {}) {diff --git a/tsconfig.json b/tsconfig.jsonindex 3ccc358..009f630 100644--- a/tsconfig.json+++ b/tsconfig.json@@ -1,17 +1,6 @@{"files": [],"references": [- { "path": "./packages/common" },- { "path": "./packages/db" },- { "path": "./packages/core" },- { "path": "./packages/observer-sdk" },- { "path": "./packages/merchant-sdk" },- { "path": "./apps/payment-api" },- { "path": "./apps/checkout-portal" },- { "path": "./apps/merchant-admin" },- { "path": "./apps/payment-help" },- { "path": "./apps/gmail-observer" },- { "path": "./apps/sms-observer" },- { "path": "./apps/control-center" }+ { "path": "./packages/common" }]}